【问题标题】:How to use DB transaction in Laravel [duplicate]如何在 Laravel 中使用数据库事务 [重复]
【发布时间】:2015-11-08 18:28:20
【问题描述】:

我正在使用 OctoberCMS,我的规则位于模型类中。当发生规则验证错误时,它们会抛出新的ModelException

尝试:

DB::beginTransaction();
try 
{
  $model = new Model;
  $model->name = $name;
  $model->save();
 
  $another = new Another;
  $another->id = $model->id;
  $another->value = $value;
  $another->save();
  // all right
  DB::commit();
}
catch( ModelException $e ) 
{
  // some rules exception with one of these models
  DB::rollback();
}

以上代码保存$model,如果在保存$another时抛出一个ModelException$model记录仍保留在数据库中。

mysql: 5.6.21

表:InnoDB

我的解决方法是:

    $model = new Model;
    $model->name = $name;
    $model->save();
    try 
    {
      $another = new Another;
      $another->id = $model->id;
      $another->value = $value;
      $another->save();
    }
    catch( ModelException $e ) 
    {
      $model->delete();
      $myerrors = $another->errors()->all();
    }

如何使 Laravel 事务在描述的情况下工作?

【问题讨论】:

  • 您可以根据关系执行$model->another()->associate($another)->save() 之类的操作。这样做你也可以放弃$model->save()

标签: php mysql laravel


【解决方案1】:

你可以试试这个:

DB::transaction(function()
{
    // Write your code here...
});

注意:事务关闭中抛出的任何异常都会导致 事务自动回滚。 Laravel Website

你也可以read this,很好的解释。

【讨论】:

  • 老兄,我确实阅读了这篇文章以及互联网上的所有其他文章。这对我使用 OctoberCMS 不起作用并且绞尽脑汁。我暂时放弃交易。但是谢谢:-)
猜你喜欢
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 2021-09-30
  • 2020-06-22
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多