2016-11-23 100 views

回答

2

未承諾將在SQL被放棄的交易。

當你拋出異常,DB::commit()永遠不會到達。您將直接進入catch()模塊,因此該事務將被丟棄(只要DB::commit()未在稍後調用)。

但是,如果您不希望在拋出異常時提交事務,我仍然總是建議在catch塊中顯式回滾事務,這將關閉該事務,並防止對將來的查詢產生影響那個執行。

try { 
    DB::beginTransaction(); 
    throw new Exception("something happened"); 
    DB::commit() 
} catch (Exception $e) { 
    Log::debug("something bad happened"); 
    DB::rollBack(); 
} 

或者使用內置的DB ::交易()與閉合時的例外是未捕獲的,這裏的文檔自動回滾:https://laravel.com/docs/5.3/database#database-transactions

+0

謝謝。它是否堅持交易並且有某種清理過程? – timbroder

+0

交易將一直處於開放狀態,直到腳本執行完畢,屆時將會有一個清理過程關閉/放棄該交易。因此,我添加了我的建議,在拋出異常時顯式回滾事務。 – Devon

+0

我可以使用Db :: commit,如果迴應一些事情,如果成功執行 –

2

如果您使用的封閉,如:

DB::transaction(function() { 
    DB::table('users')->update(['votes' => 1]); 
    DB::table('posts')->delete(); 
}); 

你會遇到內部架構驗證碼:

public function transaction(Closure $callback) 
{ 
    $this->beginTransaction(); 

    // We'll simply execute the given callback within a try/catch block 
    // and if we catch any exception we can rollback the transaction 
    // so that none of the changes are persisted to the database. 
    try { 
     $result = $callback($this); 

     $this->commit(); 
    } 

    // If we catch an exception, we will roll back so nothing gets messed 
    // up in the database. Then we'll re-throw the exception so it can 
    // be handled how the developer sees fit for their applications. 
    catch (Exception $e) { 
     $this->rollBack(); 

     throw $e; 
    } catch (Throwable $e) { 
     $this->rollBack(); 

     throw $e; 
    } 

    return $result; 
} 

所以,在日是的,你100%肯定交易將要回滾。如果您打開DB::beginTransaction();人工交易,沒有辦法,以確保即將回滾,除非你確定的東西,如:

try { 
    DB::beginTransaction(); 
    //do something 
    DB::commit(); 
} catch (\Exception $e) { 
    DB::rollback(); 
} 

如果拋出一個異常,而不抓,腳本死亡或結束打開交易,PDO將自動回滾(http://php.net/manual/en/pdo.transactions.php):

當腳本結束時,或者當一個連接即將被關閉,如果你有一個未完成的事務,PDO將自動回滾。

相關問題