php - Laravel 4 中的事务和事件

标签 php events laravel laravel-4 event-listener

当从 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/

相关文章:

php - Drupal 6 和 PHP : how to crop part of string with php

php - 使用 jquery 跨站点发布 JSON 数据

php - Laravel 搜索重复返回数据

php - 如何使用 eloquent 查询返回 JSON 响应?

php - Laravel 用户事件数据库记录器

php - 如何在我的 HTML 表单中显示选定的用户输入?

php - Docker 容器关闭脚本

vb.net - 将处理程序添加到动态创建的上下文菜单

php - jQuery 中的 JavaScript 函数参数

Javascript 检测 HTML 元素上可用的事件处理程序