2014-04-07 43 views
0

我是zf2中的新人。我做了一個創建動作,並希望獲得最後插入的id,但calender_id始終等於零。我如何獲得創建操作中的最後一個插入ID?如何獲取zf2中最後插入的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

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

相關問題