如何在zf2中获取最后插入的id?

时间:2014-04-07 08:47:16

标签: php zend-framework2 lastinsertid

我是zf2的新手。我创建了一个创建操作并希望获得最后插入的ID,但calender_id始终等于零。如何在create action中获取最后一个插入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?

1 个答案:

答案 0 :(得分:1)

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