当从 Laravel 的闭包事务函数中触发事件时,事件中的数据库操作是否也是事务的一部分还是在事务之外?
Snippet 1
Event::listen('fireme',function($data){
User::where('votes', '>', 100)->update(array('status' => 2));
});
Snippet 2
DB::transaction(function(){
User::where('votes', '>', 100)->update(array('email' => 'something@somewebsite.com'));
Event::fire('fireme',array('email' => 'something@somewebsite.com'));
});
代码段 1 是否属于代码段 2 上定义的交易?
最佳答案
我有完全相同的问题。
按照@alexandre-danault 的建议,我可以确认事件处理程序中抛出的异常(事件从事务中触发)将导致事务回滚。我认为提出这个答案可能会让您不必先运行自己的测试。这是我的代码片段(我没有使用事务的关闭形式):
// I throw an exception from within this event handler
Event::listen('transaction.statusChange', 'TransactionHandler@onStatusChange');
// Here's the transaction that fires the event
DB::beginTransaction();
try {
$this->status = $status;
if (!$this->save()){
throw new Exception('...');
}
Event::fire('transaction.statusChange', ['transaction' => $this, 'status' => $status]);
} catch(Exception $e){
DB::rollback();
// Log exception
return false;
}
DB::commit();
关于php - Laravel 4 中的事务和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17177844/