简体   繁体   中英

Transactions and Events in Laravel 4

When an Event is fired from within the Laravel's closure transaction function, are the Database operations within the Events also part of the Transaction or are they outside of it?

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'));
    });

Does Snippet 1 belong to the transaction defined on Snippet 2?

I had exactly the same question.

Following the suggestion of @alexandre-danault, I can confirm that exceptions thrown within an event handler, where the event is fired from within a transaction, will cause the transaction to rollback. I figured putting this answer up might save you having to run your own test first. Here are my code snippets (I'm not using the closure form of transactions):

// 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();

If you only have one database connection, and you are within a transaction, then everything you do in the database must be a part of that transaction. Laravel does not open additional database connections for events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM