Magento 捕获异常并回滚数据库事务

2021-12-19 00:00:00 model database transactions php magento

我正在研究 Magento 模块,需要知道是否可以回滚一系列模型保存.基本上,我有五个模型加上我模块中的几个模型,我需要一个接一个地保存:

I'm working on a Magento module and need to know if it's possible to roll back a series of model saves. Basically, I have five models plus several from my module that I need to save one after the other:

admin/role
admin/user
core/website
core/store_group
core/store
mymodule/model1
mymodule/model2

我的问题是,每当这些模型中的任何一个抛出异常时,我都需要进入 MySQL 并手动删除所有已保存的行.这是非常没有成效的.

My problem is that whenever any of these models throw an exception, I need to go into MySQL and manually delete all the rows that were saved. This is very unproductive.

我很确定 Magento 没有我可以在我的上下文中访问的回滚过程.比如我查看了Mage_Core_Model_Abstract,在save方法中,回滚机制都是受保护的.

I'm pretty sure that Magento doesn't have a rollback procedure that I can access in my context. For example, I looked in Mage_Core_Model_Abstract and in the save method, the rollback mechanisms are all protected.

那么,我的问题是,在 Magento 中进行数据库事务是否有一些我应该注意的最佳实践?

So, my question is, is there some best practice for doing database transactions in Magento that I should be aware of?

推荐答案

我在核心代码中看到了以下内容,看起来正是您订购的.

I've seen the following used in core code, and it looks like its just what you ordered.

$transactionSave = Mage::getModel('core/resource_transaction');
$transactionSave->addObject($model_one)
$transactionSave->addObject($model_two)
$transactionSave->save();

core/resource_transaction 对象允许您添加 Magento 对象,并对它们执行批量保存.试一试,我很想在评论中听到这对你有用或没用.

The core/resource_transaction object allows you to add Magento objects, and perform a mass save on them. Give that a try, and I'd love to hear how this does, or doesn't, work for you in the comments.

相关文章