In most cases, you should use the model method to query your database.
Model::query() exists to execute complex queries that will be more complex than using model methods, or in some cases when you have no choice.
In your case, this is very useful, because Model::save() launches a callback in a framework that sets the Model::id attribute for you.
So, this allows you to return it immediately:
if ($this->Menu->save($data)) { $lastId = $this->Menu->id; }
A WARNING!
On the other hand, and as said by other answers, there is the following method:
Model::getLastInsertId()
But YOU SHOULD BE VERY CAREFUL with this method and YOU SHOULD NOT USE THIS IN THIS USE because it inserted LAST , but NOT the last one you just inserted in the previous code statement!
If the user (during another parallel request on the server) saves the data between save() and getLastInsertId() , he will return this second user!
THUS, the following BAD answers respond for this use case :
- stack overflow
- stack overflow
- stack overflow
- stack overflow
Rémi becheras
source share