如何在 Laravel 5.3 中回滚事务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41915788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:13:29  来源:igfitidea点击:

How to rollback a transaction in Laravel 5.3?

phplaraveltransactions

提问by Jaylen

I am trying to create a demo crud using a Laravel 5.3. I wrote a controller's method to handle the update . This method should always starts transaction, and always rollback the changes. So the changes never commit into the database.

我正在尝试使用 Laravel 5.3 创建一个演示 crud。我写了一个控制器的方法来处理更新。此方法应始终启动事务,并始终回滚更改。所以更改永远不会提交到数据库中。

Here is how my method looks like

这是我的方法的样子

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');
}

Unfortunately, the update still gets committed every time. How can I correctly begin a transaction and then roll back the changes?

不幸的是,更新仍然每次都会提交。如何正确开始事务然后回滚更改?

回答by Omar

you can rollback in case the code that before commit throws an exception.

如果提交前的代码抛出异常,您可以回滚。

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();
}

}

you can check this answerand here is the documentation about transactions

您可以查看此答案,这里是有关交易文档