如果发生异常,Laravel DB Transaction会发生什么?
问题描述:
我认为*交易只是丢弃。这是否准确?如果发生异常,Laravel DB Transaction会发生什么?
我用mysql
例子:
try {
DB::beginTransaction();
throw new Exception("something happened");
DB::commit()
} catch (Exception $e) {
Log::debug("something bad happened");
}
感谢
答
未承诺将在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
答
如果您使用的封闭,如:
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将自动回滚。
谢谢。它是否坚持交易并且有某种清理过程? – timbroder
交易将一直处于开放状态,直到脚本执行完毕,届时将会有一个清理过程关闭/放弃该交易。因此,我添加了我的建议,在抛出异常时显式回滚事务。 – Devon
我可以使用Db :: commit,如果回应一些事情,如果成功执行 –