Php Laravel DB::transaction()返回值

Php Laravel DB::transaction()返回值,php,laravel,Php,Laravel,这是我第一次使用DB::transaction(),但是如果事务失败或成功,它究竟是如何工作的呢?在下面的示例中,我是否必须手动分配一个值以返回true,或者如果失败,该方法将返回false,或者完全退出事务(因此跳过其余的代码)?文档在这方面没有太大帮助 use Exception; use DB; try { $success = DB::transaction(function() { // Run some queries }); print_

这是我第一次使用
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.';
}
解决方案 我写下了这个解决方案,供其他可能感到疑惑的人参考

由于我更关心的是根据查询的成功返回布尔值,因此经过一些修改后,它现在根据其成功返回
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
永远不会返回,因为如果查询出错,则会立即触发
捕获
,返回
false
。感谢@ilaijin显示,如果出现问题,将抛出
异常
对象。

通过查看
函数事务
,它在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
,这是回调的结果,则抛出异常(回滚后)。您还可以使用以下命令

DB::rollback();

有没有办法模拟失败的事务?意思是你想捕获
catch(异常$e){echo'Uh-oh.;}
?对不起,没有必要。我一时忘记了扔东西的事。