2015-02-07 78 views
0

在这里,我已经使用CakePHP的JS助手发送数据后,插入一个数据,我需要为进一步work.Here这最后的ID我都试过娄代码在AddcontrollerCakePHP的getLastInsertId不工作

if ($this->Patient->save($this->request->data)) { 
       $lastid=$this->Patient->getLastInsertId(); 
       $patient=$this->Patient->find('all',array(
       'conditions'=>array('Patient.id'=>$lastid), 
       'recursive' => -1 
)); 
$this->set('patient', $patient); 

} 

在add.ctp我试过了波纹管代码,但我没有在这里得到最后一个ID。

<?php foreach ($patient as $patient): ?> 
    <?php echo h($patient['Patient']['id']); ?> 
<?php endforeach; ?> 

回答

2

使用

if ($this->Patient->save($this->request->data)) { 
    $id = $this->Patient->id; 
    $patient=$this->Patient->find('all',array('conditions'=>array('Patient.id'=>$id),'recursive' => -1)); 

$this->set->('patient', $patient); 
//If you are saving the record with ajax which it looks like you 
//might be from your question you will need the following instead 
//of $this->set->('patient', $patient); try: 

return json_encode($patient); 

你那么还需要更新您的JS Ajax调用,你将有一个JSON数组进行解码,以便与jQuery解析它并追加它放回你的看法。

Cake通过简单地添加$ id = $ this-> MyModel-> id;总是会给你刚刚保存的记录的id。您可以使用该ID来查询记录。

2

方法getLastInsertId()返回刚刚保存的记录的ID。

如果需要此ID在你看来只是保存之后,你必须首先设置该变量在您的控制器像$this->set(compact('lastid','patient');,然后在视图中使用<?php echo $lastid; ?>

0

尝试下面的代码,

1)控制器:

$lastid=$this->Patient->getLastInsertId(); 

$this->set(compact('lastid','patient'); 

然后在查看flie中使用$lastid

     OR 

2)控制器:

$lastid=$this->Patient->getLastInsertId(); 
$patient['Patient']['last_id'] = $lastid; 

然后使用您的视图文件$patient['Patient']['last_id']

希望它能帮助你。