【发布时间】: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()。