CakePHP: Is getLastInsertId Method Safe

If I save the model, does getLastInsertId() return the last insert identifier or return the identifier from the row I just saved. In other words, if I do this:

 $this->Model->save($this->data); __thisFunctionTakesAVeryLongTimeToExecute(); $insertId = $this->Model->getLastInsertId(); 

Does getLastInsertId() return the identifier from the data I saved, 2 lines above. Or does it return the last identifier that was created?

+4
source share
3 answers

not sure about lastInsertId, but ... why don't you use $this->Model->id instead? after saving the information, the last inserted identifier is saved there

+3
source

I use Model::getLastInsertID() all the time the same as you try to use it, and there were no problems. $this->Model->id essentially does the same immediately after saving.

But keep in mind that $this->Model->id is writable (i.e. $this->Model->id = <some_number> ) and does not always represent the identifier of the record just inserted. Whereas Model::getLastInsertID() does.

+2
source

Model::getLastInsertID retrieves the last inserted identifier from the current connection. Thus, it is safe until you paste from the same connection.

To make this a little more understandable, I believe that you need to think about how to provoke this error, because it is not so simple. Two different browsers on the same machine will use different connections. I'm not sure what should happen in the same browser with different tabs. As before, I never had this problem.

The safest way can be called by the store procedure, which returns the inserted identifier, but this is not a wireframe approach to do something.

+1
source

All Articles