CakePHP:getLastInsertId方法安全吗
如果我保存模型,getLastInsertId()
是否返回最后一个插入 ID,或者返回我刚刚保存的行的 ID。换句话说,如果我这样做:
$this->Model->save($this->data);
__thisFunctionTakesAVeryLongTimeToExecute();
$insertId = $this->Model->getLastInsertId();
getLastInsertId()
是否会从我在上面保存的两行数据中返回 ID。或者它是否返回创建的最新 ID?
If I save a model, does the getLastInsertId()
return the last insert ID or does it return the ID from the row I've just saved. In other words if I do this:
$this->Model->save($this->data);
__thisFunctionTakesAVeryLongTimeToExecute();
$insertId = $this->Model->getLastInsertId();
Does getLastInsertId()
return the ID from the data I've saved 2 lines above. Or does it return the latest ID that's created?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不确定 lastInsertId 但是...为什么不使用
$this->Model->id
呢?保存信息后,最后插入的 id 会存储在那里not sure about lastInsertId but... why dont you use
$this->Model->id
instead?? after saving the info, the last inserted id gets stored there我一直使用 Model::getLastInsertID() ,就像您尝试使用它一样,没有遇到任何问题。
$this->Model->id
本质上在保存后立即执行相同的操作。但请记住
$this->Model->id
是可写的(即$this->Model->id =
)并且并不总是代表您刚刚插入的记录的 ID。而Model::getLastInsertID()
则可以。I use
Model::getLastInsertID()
all of the time much the same way that you are attempting to use it and have had no issues.$this->Model->id
essentially does the same thing right after a save.But keep in mind that
$this->Model->id
is writable (i.e.$this->Model->id = <some_number>
) and doesn't always necessarily represent the ID of the record that you just inserted. Whereas,Model::getLastInsertID()
does.Model::getLastInsertID
从当前连接中检索最后插入的 ID。因此,当您不从同一连接插入时,它是安全的。为了更清楚一点,我相信你必须考虑如何引发这个错误,因为它并不那么简单。同一台机器上的两个不同的浏览器将使用不同的连接。我不确定在具有不同选项卡的同一浏览器上会发生什么。正如其他人之前所说,我从来没有遇到过这个问题。
最安全的方法可能是通过返回插入的 id 的存储过程,但这不是执行操作的框架方法。
Model::getLastInsertID
retrieves the last inserted ID from the current connection. So It's safe while you are not inserting from the same connection.To make it a little bit more clear, I believe you have to think how to provoke this error because it's not so simple. Two different browsers on the same machine will use different connections. I'm not sure what should happen on the same browser with different tabs. As other one said before, I never had that problem.
The safest way, may be trough a store proceduce that returns the inserted id, but it's not the framework approach to do things.