我正在尝试使用Laravel 5.3创建一个演示文稿。我写了一个控制器的方法来处理更新。此方法应始终启动事务,并始终回滚更改。因此,更改永远不会提交到数据库中。
以下是我的方法的样子
public function update($id, Request $request)
{
DB::beginTransaction();
$this->affirm($request);
$biography = Biography::findOrFail($id);
$data = $request->all();
$biography->update($data);
Session::flash('success_message', 'Biography was updated! However, because this is a demo the records are not persisted to the database.');
DB::rollBack();
return redirect()->route('demo.index');
}
不幸的是,每次都会提交更新。如何正确开始事务然后回滚更改?
答案 0 :(得分:2)
如果提交之前的代码抛出异常,您可以回滚。
public function update($id, Request $request)
{
DB::beginTransaction();
try{
$this->affirm($request);
$biography = Biography::findOrFail($id);
$data = $request->all();
$biography->update($data);
Session::flash('success_message', 'Biography was updated! However, because this is a demo the records are not persisted to the database.');
//if there is not error/exception in the above code, it'll commit
DB::commit();
return redirect()->route('demo.index');
} catch(\Exception $e){
//if there is an error/exception in the above code before commit, it'll rollback
DB::rollBack();
return $e->getMessage();
}
}