如何在Yii事件中使用交易 [英] How to use transactions in Yii event
问题描述
我知道,如何在纯粹的环境中使用交易DAO 或 ActiveModel 中,其中在调用$model->save()
并滚动交易之前启动事务返回任何异常.
I know, how to use transactions in pure DAO or in ActiveModel, where transaction is initiated before call to $model->save()
and rolled back upon any exception.
但是,如果我可以访问的唯一代码位置(无论为何),则如何使用事务是 Yii事件?
But how to use transactions, if the only place of code I have access to (no matter, why) is Yii event?
public function beforeDelete()
{
foreach($this->menuItems as $menuItem) $menuItem->delete();
return parent::beforeDelete();
}
如果我在那里发起事务,捕获可能的异常并在其上回滚整个事务,那么将仅回滚关系模型的删除(在这里:菜单项).这不会阻止(回滚)删除主记录.
If I initiate transaction there, capture possible exception and rollback entire transaction upon it, then only deletion of relational models (here: menu items) will be rolled back. It will not prevent (roll back) deletion of master record.
是否可以通过在自己的beforeDelete
中返回FALSE
来防止主记录的删除,如果发生异常,我在这里需要注意的一切吗?还是应该完全避免在Yii事件中进行交易?
Does preventing deletion of master record, by returning FALSE
in my own beforeDelete
in case of exception, is all I need to take care here? Or should I avoid transactions at all in Yii events?
推荐答案
关于覆盖保存方法:
public function save($runValidation=true,$attributes=null)
{
$transaction=$this->getDbConnection()->beginTransaction();
try
{
$result = parent::save($runValidation,$attributes);
if($result)
$transaction->commit();
else
$transaction->rollback();
}
catch(Exception $e)
{
$transaction->rollback();
$result = false;
}
return $result;
}
这篇关于如何在Yii事件中使用交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!