cakephp getLastInsertId不起作用

时间:2015-02-07 11:47:02

标签: cakephp

这里我使用了cakephp js helper来发送数据,在插入一个数据之后我需要这个最后一个id来进行更远的工作。我在Addcontroller中尝试了下面的代码

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; ?>

3 个答案:

答案 0 :(得分: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-&gt; MyModel-&gt; id来为您提供刚刚保存的记录的ID;您可以使用id来查询记录。

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

尝试以下代码,

1)在控制器中:

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

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

然后在View flie中使用$lastid

                      OR

2)在控制器中:

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

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

希望它会对你有帮助。