Magento 最后在事务中间插入 id
我正在 Magento 中使用事务。 我需要对所有后续查询使用第一个插入查询的primeryKey。
$model1->setfield1()
->setField2();
$transaction->addObject($model1);
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$lastInsertId = $connection->fetchOne('SELECT last_insert_id()'); // return 0
$model2->setfield3($lastInsertId )
$model3->setfield4($lastInsertId )
$transaction->addObject($model2);
$transaction->addObject($model3);
$transaction-Save();
$lastInsertId2 = $connection->fetchOne('SELECT last_insert_id()'); // returns correct result
如何在保存交易之前获取最后插入的ID
I am using transactions in Magento.
I need to use primeryKey of first insert query to all my subsequent queries.
$model1->setfield1()
->setField2();
$transaction->addObject($model1);
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
$lastInsertId = $connection->fetchOne('SELECT last_insert_id()'); // return 0
$model2->setfield3($lastInsertId )
$model3->setfield4($lastInsertId )
$transaction->addObject($model2);
$transaction->addObject($model3);
$transaction-Save();
$lastInsertId2 = $connection->fetchOne('SELECT last_insert_id()'); // returns correct result
how to get last inserted id before saving the transaction
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我猜当事务尚未提交时,PDO(magento 使用)无法获取last_inserted_id。我想你应该尝试像那里这样的普通sql尝试使用嵌套事务。
I guess PDO (which magento uses) can't get last_inserted_id while transaction isn't commited yet. I guess you should either try plain sql like there or try use nested transactions.
泰伊这个:
$lastInsertId = $connection->lastInsertId();
Tyy this:
$lastInsertId = $connection->lastInsertId();
不确定交易的情况,但我通常这样做:
Not sure about the case with transactions, but I usually do it like this:
在调用
save()
方法之前,Magento 事务不会更改数据库中的数据:addObject()
只是将新对象添加到事务的注册表中 (\Mage_Core_Model_Resource_Transaction:: $_objects
)。$model1->save()
方法将在$transaction->save()
上调用。在调用$transaction->save()
之前不会执行任何 INSERT 操作。Magento transaction does not change data in the DB until you call
save()
method:addObject()
just adds new object to the transaction's registry (\Mage_Core_Model_Resource_Transaction::$_objects
).$model1->save()
method will be called on$transaction->save()
. No INSERT operation is performed before$transaction->save()
call.