What is the equivalent to getLastInsertId() in Cakephp?

后端 未结 22 757
囚心锁ツ
囚心锁ツ 2020-11-28 11:00

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:

f         


        
22条回答
  •  孤街浪徒
    2020-11-28 11:26

    Try using this code in your model class (perhaps in AppModel):

    function get_sql_insert_id() {
       $db =& ConnectionManager::getDataSource($this->useDbConfig);
       return $db->lastInsertId();
    }
    

    Caveat emptor: MySql's LAST_INSERT_ID() function only works on tables with an AUTO_INCREMENT field (otherwise it only returns 0). If your primary key does not have the AUTO_INCREMENT attribute, that might be the cause of your problems.

提交回复
热议问题