簡體   English   中英

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

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

我是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?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM