简体   繁体   English

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

[英]How to get last inserted id in zf2?

I am new in zf2. 我是zf2的新手。 I make a create action and want to get last inserted id but calender_id always equal to zero. 我执行创建操作,并希望获取最后插入的ID,但calender_id始终等于零。 How can I get the last insert id in create action ? 如何获取create action中的最后一个插入ID?

Here is my code: 这是我的代码:

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');
        }
    }

how i get last inserted id? 我如何获得上次插入的ID?

If your calendarTable extends TableGateway you can use $calendarTable->getLastInsertValue() to get the last insert id. 如果您的calendarTable扩展了TableGateway,则可以使用$calendarTable->getLastInsertValue()获取最后一个插入ID。 You can also use this method in your saveCalendar method. 您也可以在saveCalendar方法中使用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM