【问题标题】:Laravel transaction does not rollback when none db exception happens当没有数据库异常发生时,Laravel 事务不会回滚
【发布时间】:2019-11-19 16:53:19
【问题描述】:

这是我的代码:

 DB::transaction(function () use ($r, $certificate, $candidate) {

             UserCertificate::create([
                 'user_id' => $r['user_id'],
                 'certificate_id' => $certificate->id,
                 'issue_date' => Carbon::now()
              ]);

             // create badge
             $this->createCandidateBadge($candidate, $certificate);

});

创建候选人徽章时发生异常:$this->createCandidateBadge

但是当我看到user_certificates 表时,会创建一个证书!除非成功创建徽章,否则我不想在 DB 中创建证书!

【问题讨论】:

  • 使用 try catch 并手动处理提交回滚

标签: php mysql laravel transactions


【解决方案1】:

您可以使用 try 和 catch 块进行自定义事务功能以及手动提交和回滚,如下所示:

DB::beginTransaction();

try{
        UserCertificate::create([
             'user_id' => $r['user_id'],
             'certificate_id' => $certificate->id,
             'issue_date' => Carbon::now()
          ]);

         // create badge
         $this->createCandidateBadge($candidate, $certificate);

         DB::commit();

}catch (\Exception $e){
    DB::rollBack();
}

任何类型的异常都会被捕获,然后所有的数据库操作都会被回滚。如果没有异常数据将被保存。

【讨论】:

    【解决方案2】:

    根据文档Database Transactions

    如果在事务闭包中抛出异常,则 事务会自动回滚。

    您应该尝试通过try...catch 将您的逻辑包装在DB::transaction 中,如下所示:

    DB::transaction(function () use ($r, $certificate, $candidate) {
        try {
             UserCertificate::create([
                 'user_id' => $r['user_id'],
                 'certificate_id' => $certificate->id,
                 'issue_date' => Carbon::now()
             ]);
    
             // create badge
             $this->createCandidateBadge($candidate, $certificate);
    
        } catch (\Exception $e) {
             // Response with Error here
        }
    });
    // Response with success
    

    也检查这个问题Laravel: Using try…catch with DB::transaction()

    享受:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      相关资源
      最近更新 更多