【问题标题】:How to get last inserted id in zf2?如何在 zf2 中获取最后插入的 id?
【发布时间】:2014-04-07 08:47:15
【问题描述】:

我是 zf2 的新手。我进行了创建操作并希望获得最后插入的 id,但 calender_id 始终等于零。如何在创建操作中获取最后一个插入 ID?

这是我的代码:

public function createAction()
    {
        if ($this->zfcUserAuthentication()->hasIdentity())
        {
            $form = new CalendarForm();
            $form->get('user_id')->setValue($this->zfcUserAuthentication()->getIdentity()->getId());
            $form->get('submit')->setValue('Add');

            $request = $this->getRequest();
            if ($request->isPost()) {
                $calendar = new Calendar();
                $form->setInputFilter($calendar->getInputFilter());
                $form->setData($request->getPost());

                if ($form->isValid()) {
                    $calendar->exchangeArray($form->getData());
                    $this->getCalendarTable()->saveCalendar($calendar);
                    if($request->isXmlHttpRequest()) {
                        //$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
                        //$calender = new \Calendar\Model\Calendar($dm);
                        $response = new Response();
                        $calender_id = $calendar->calendar_id;
                        $userid =$calendar->user_id;
                        $title=$calendar->title;
                        $description=$calendar->description;
                        $output = array('success' => true, 'calendar_id' => $calender_id, 'user_id' => $userid, 'title' => $title, 'description' => $description);
                        //$response->headers->set('Content-Type', 'application/json');
                        $response->setContent(json_encode($output));
                        return $response;

                    }
                    return $this->redirect()->toRoute('calendar');

                }
            }
            return array('form' => $form);
        }
        else
        {
            $this->redirect()->toRoute('zfcuser/login');
        }
    }

我如何获得最后插入的 id?

【问题讨论】:

    标签: php zend-framework2 lastinsertid


    【解决方案1】:

    如果您的 calendarTable 扩展 TableGateway,您可以使用 $calendarTable->getLastInsertValue() 获取最后一个插入 ID。您也可以在 saveCalendar 方法中使用此方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多