开发者

Does the $this->{Model}->id after a db insertion always return the id of the last inserted record

开发者 https://www.devze.com 2023-03-18 18:40 出处:网络
Cakephp queries SELECT LAST_INSERT_ID() AS insertID to get the last insert id after the insertion to get the \'id\' of the inserted record, but what if in some other parallel process another record w

Cakephp queries SELECT LAST_INSERT_ID() AS insertID to get the last insert id after the insertion to get the 'id' of the inserted record, but what if in some other parallel process another record was added before the above 开发者_开发问答query is executed?


In MySQL, LAST_INSERT_ID() is connection-specific, otherwise it would lead to many unwanted consequences. If another process adds an record, than it is using another connection, so the return value for LAST_INSERT_ID() is not changed for your current connection.

I don't think it is handled differently in other RDBMS and you don't mention what database system you use.

In the words of the MySQL Doc:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

See the MySQL docs for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号