Laravel DB::transaction() 返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20176153/
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
Laravel DB::transaction() return value
提问by enchance
It's my first time to use DB::transaction()
but how exactly does it work if a transaction fails or is successful? In the example below, do I have to manually assign a value to return true
, or if it fails will the method either return false
or totally exit the transaction (therefore skipping the rest of the code)? The docs aren't so helpful on this.
这是我第一次使用,DB::transaction()
但如果交易失败或成功,它究竟是如何工作的?在下面的示例中,我是否必须手动为 return 分配一个值true
,或者如果它失败,该方法将返回false
还是完全退出事务(因此跳过其余代码)?文档对此没有太大帮助。
use Exception;
use DB;
try {
$success = DB::transaction(function() {
// Run some queries
});
print_r($success);
} catch(Exception $e) {
echo 'Uh oh.';
}
Solution
解决方案
I wrote down this solution for others who might be wondering.
我为其他可能想知道的人写下了这个解决方案。
Since I was more concerned about returning a boolean value depending on the success of my query, with a few modifications it now returns true/false
depending on its success:
由于我更关心根据查询的成功返回一个布尔值,经过一些修改,它现在true/false
根据查询的成功返回:
use Exception;
use DB;
try {
$exception = DB::transaction(function() {
// Run queries here
});
return is_null($exception) ? true : $exception;
} catch(Exception $e) {
return false;
}
Take note that the variable $exception
is never returned since if something goes wrong with your query, the catch
is immediately triggered returning false
. Thanks to @ilaijin for showing that an Exception
object is thrown if something goes wrong.
请注意,该变量$exception
永远不会返回,因为如果您的查询出现问题,将catch
立即触发返回false
. 感谢@ilaijin 展示了Exception
如果出现问题会抛出一个对象。
采纳答案by ilpaijin
By giving a look at function transaction
it does its process inside a try/catch block
通过查看function transaction
它在 try/catch 块中执行的过程
public function transaction(Closure $callback)
{
$this->beginTransaction();
// We'll simply execute the given callback within a try / catch block
// and if we catch any exception we can rollback the transaction
// so that none of the changes are persisted to the database.
try
{
$result = $callback($this);
$this->commit();
}
// If we catch an exception, we will roll back so nothing gets messed
// up in the database. Then we'll re-throw the exception so it can
// be handled how the developer sees fit for their applications.
catch (\Exception $e)
{
$this->rollBack();
throw $e;
}
So throws an Exception (after the rollback) if fails or returns $result
, which is the result of your callback
因此,如果失败或返回$result
,则抛出异常(回滚后),这是回调的结果
回答by LeRoy
You can also use the following
您还可以使用以下
DB::rollback();