这是我第一次使用,DB::transaction()但如果交易失败或成功,它究竟是如何运作的?在下面的示例中,我是否必须手动为返回值分配值true,或者如果失败将返回false或完全退出事务(因此跳过其余代码)?文档对此没有那么有用.
use Exception;
use DB;
try {
$success = DB::transaction(function() {
// Run some queries
});
print_r($success);
} catch(Exception $e) {
echo 'Uh oh.';
}
Run Code Online (Sandbox Code Playgroud)
我为其他可能想知道的人写下了这个解决方案.
因为我更关心根据查询的成功返回一个布尔值,稍微修改一下,它现在返回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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,$exception永远不会返回变量,因为如果查询出现问题,catch则会立即触发返回false.感谢@ilaijin表示Exception如果出现问题就抛出一个对象.
ilp*_*jin 10
通过查看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;
}
Run Code Online (Sandbox Code Playgroud)
因此,如果失败或返回$result,则抛出异常(在回滚之后),这是回调的结果