Laravel DB::transaction() 返回值

14
这是我第一次使用DB::transaction(),但如果事务失败或成功,它到底是如何工作的呢?在下面的示例中,我是否需要手动分配一个值来返回true,或者如果它失败了,该方法会返回false或完全退出事务(从而跳过其余的代码)?文档对此并没有提供太多帮助。
use Exception;
use DB;

try {
    $success = DB::transaction(function() {
        // Run some queries
    });

    print_r($success);

} catch(Exception $e) {
    echo 'Uh oh.';
}
4个回答

14

通过查看transaction函数,它会在try/catch块内进行处理。

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

如果失败,就会抛出一个异常(在回滚之后),否则返回$result,它是您回调的结果。


有没有一种方法可以模拟一个失败的交易? - enchance
你想要捕获 catch(Exception $e) { echo 'Uh oh.'; } 的意思是什么? - ilpaijin
1
抱歉,不用了。我一时忘记了throw - enchance

3
如果您想使用 Laravel 默认的事务处理方式且不需要手动处理,可以使用简短的版本。
$result = DB::transaction(function () { 
    // logic here
    return $somethingYouWantToCheckLater;
});

0
你也可以使用以下内容。
DB::rollback();

0

(代表问题作者发布,将解决方案移至答案空间)

由于我更关心根据查询的成功与否返回布尔值,经过一些修改,现在它返回true/false,取决于其成功与否:

use Exception;
use DB;

try {
  $exception = DB::transaction(function() {
    // Run queries here
  });

  return is_null($exception) ? true : $exception;

} catch(Exception $e) {
    return false;
}

请注意,变量$exception从未返回,因为如果查询出现问题,catch会立即触发并返回false。感谢@ilaijin展示了如果出现问题,会抛出一个Exception对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接