我可以在cakephp 3.x中获得最后插入的ID吗?

时间:2017-04-13 10:13:59

标签: php cakephp

我想在蛋糕php 3中插入最后一个id。

如果($这 - >请求 - '是( '后')){

       $this->loadModel('MyPlaylists');

                    $playlistData = [];
                    $playlistData["user_id"] = $_POST['user_id'];
                    $playlistData["play_list_name"] =  $_POST['play_list_name'];
                    $playlistData["section"] = $_POST['section'];
                    $playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
                    $playlistData["status"] = 'active';
                    $playlist_en = $this->MyPlaylists->newEntity();  
                    $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
                    $this->MyPlaylists->save($playlist_en);
                    $id=$this->MyPlaylists->id;
                }

我也尝试过:

$id=$this->MyPlaylists->lastInsertedId;

但它给出了如下截图的错误: enter image description here

2 个答案:

答案 0 :(得分:1)

您的代码需要进行一些微调。

$playlist_en    =    $this->MyPlaylists->newEntity();  
$playlist_en    =    $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid        =    $this->MyPlaylists->save($playlist_en);
if ($isValid) {
    $id    =    $playlist_en->id;
    debug($id); // Check your last insert id
} else {
    pr($playlist_en->errors()); // Check errors
}

答案 1 :(得分:0)

进行查询,选择在DESC中排序的查询的第一个元素。方式

$newPlaylist = $this->Playlists->find('all',['order' => ['Playlists.id' => 'DESC']])->select(['id']);