laravel DB::beginTransaction() 和 DB::transaction() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39178390/
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 14:22:27  来源:igfitidea点击:

What is the difference between DB::beginTransaction() and DB::transaction()?

phpmysqllaraveltransactionslaravel-5.2

提问by Hamed Kamrava

I'm using Laravel 5.2.

我正在使用 Laravel 5.2。

I would like to know what are the differences between :

我想知道它们之间有什么区别:

  1. DB::beginTransaction()and DB::transaction()
  2. DB::commitTransction()and DB::commit()
  3. DB::rollbackTransction()and DB::rollback()
  1. DB::beginTransaction()DB::transaction()
  2. DB::commitTransction()DB::commit()
  3. DB::rollbackTransction()DB::rollback()

Any helps would be appreciated.

任何帮助将不胜感激。

回答by Parziphal

DB::beginTransaction()will only begin a transaction, while for DB::transaction()you must pass a Closure function that will be executed insidea transaction.

DB::beginTransaction()只会开始一个事务,而DB::transaction()你必须传递一个将事务执行的闭包函数。

So this:

所以这:

DB::transaction(function() {
    // Do something and save to the db...
});

is the same as this:

与此相同:

// Open a try/catch block
try {
    // Begin a transaction
    DB::beginTransaction();

    // Do something and save to the db...

    // Commit the transaction
    DB::commit();
} catch (\Exception $e) {
    // An error occured; cancel the transaction...
    DB::rollback();

    // and throw the error again.
    throw $e;
}

As you can see, DB::transaction()is a "helper" function to avoid writing code to catch errors, begin a transaction, commit the transaction, and optionally rollback (cancel the transaction) if an error occured.

如您所见,DB::transaction()是一个“帮助”函数,可避免编写代码来捕获错误、开始事务、提交事务,以及在发生错误时可选地回滚(取消事务)。

If you have a more complex logic, or need an specific behaviour, you will manually build your transaction; if your logic is rather simple, DB::transaction()is the way to go.

如果您有更复杂的逻辑,或者需要特定的行为,您将手动构建您的交易;如果您的逻辑相当简单,那DB::transaction()就是要走的路。

As for DB::commitTransaction()and DB::rollbackTransaction(), I can't find information.

至于DB::commitTransaction()DB::rollbackTransaction(),我找不到信息。

It's a good practice to check the source code of the things you use, because you will learn how they are written, as well as how to write. Here's the filewith the source for these methods.

检查您使用的东西的源代码是一个很好的做法,因为您将了解它们是如何编写的,以及如何编写。这是这些方法的源文件