Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the last insert ID in CakePHP 3.0?

Tags:

Working with the CakePHP 3.0 beta, seems like a simple problem, but I've searched through the docs and can't find anything. After inserting a new record using $this->Model->save(), I'd like to the get the auto_increment primary key ID of the newly created record.

With Cake 2.x, I could do:

$record_id=$this->ModelName->id;

or

$record_id=$this->ModelName->getLastInsertID();

However neither of those seems to work in CakePHP 3.0.

Thanks

like image 852
ben921 Avatar asked Sep 24 '14 21:09

ben921


3 Answers

Finally found the answer, if anybody else runs into this do:

$result=$this->ModelName->save($whatever); $record_id=$result->id; 
like image 130
ben921 Avatar answered Oct 10 '22 02:10

ben921


to cakephp3.X I Found this:

if ($articlesTable->save($article)) {     // The $article entity contains the id now     $id = $article->id; } 

http://book.cakephp.org/3.0/en/orm/saving-data.html#inserting-data

like image 36
Elton Baroncello Avatar answered Oct 10 '22 00:10

Elton Baroncello


You can solve this issue following way.

For CakePHP 3.x

$result = $this->ModelName->save($this->request->data);
$insertedId = $result->id;

For CakePHP 2.x

$this->ModelName->save($this->request->data);
$insertedId = $this->ModelName->getLastInsertId();
like image 32
Faisal Avatar answered Oct 10 '22 01:10

Faisal