2013-06-18 41 views
3

當一個事件從Laravel的關閉交易功能內發射,是活動也是交易的一部分內的數據庫操作或者是他們之外呢?交易和事項在Laravel 4

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' => '[email protected]')); 
      Event::fire('fireme',array('email' => '[email protected]')); 
    }); 

代碼段1是否屬於Snippet 2上定義的事務?

+1

這聽起來真的微不足道的測試,只是提高連接異常監聽器裏面,看看交易的其餘部分回滾或COMMITED。 –

回答

1

我有完全一樣的問題。

繼@亞歷山大 - danault的建議,我可以證實,事件處理程序,該事件從事務中燃中拋出的異常,將導致事務回滾。我想這個答案可能會讓你不得不先運行自己的測試。這裏是我的代碼片段(我不使用交易的封閉形式):

// I throw an exception from within this event handler 
Event::listen('transaction.statusChange', '[email protected]'); 

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

如果你只有一個數據庫連接,你是一個事務中,然後在數據庫中所做的一切必須是該交易的一部分。 Laravel不會爲事件打開其他數據庫連接。