【问题标题】:Laravel DB::transaction() return valueLaravel DB::transaction() 返回值
【发布时间】:2021-10-10 23:59:13
【问题描述】:

这是我第一次使用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 永远不会返回,因为如果您的查询出现问题,catch 会立即触发返回 false。感谢@ilaijin 表明如果出现问题会抛出一个Exception 对象。

【问题讨论】:

  • 谢谢。您的解决方案运行良好。

标签: php laravel


【解决方案1】:

通过查看function 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,则抛出异常(回滚后),这是您回调的结果

【讨论】:

  • 有没有办法模拟失败的交易?
  • 意思是你想抓catch(Exception $e) { echo 'Uh oh.'; }
  • 抱歉,不需要。我暂时忘记了throw
【解决方案2】:

如果你想使用 Laravel 自带的默认事务方法而不需要手动处理,有一个简短的版本。

$result = DB::transaction(function () { 
    // logic here
    return $somethingYouWantToCheckLater;
});

【讨论】:

    【解决方案3】:

    你也可以使用下面的

    DB::rollback();
    

    【讨论】:

      猜你喜欢
      • 2014-09-16
      • 2014-05-19
      • 2017-05-25
      • 1970-01-01
      • 2013-06-09
      • 2020-04-17
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      相关资源
      最近更新 更多