gpt4 book ai didi

php - 如何在 Laravel 中使用数据库事务

转载 作者:行者123 更新时间:2023-11-29 01:54:53 24 4
gpt4 key购买 nike

<分区>

我正在使用 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

tables: 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 事务在描述的情况下工作?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com