这是我第一次使用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.';
}
我为其他可能想知道的人写下了这个解决方案。
由于我更关心根据查询的成功返回一个布尔值,只需稍加修改就可以返回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;
}
请注意,永远不会返回变量$exception
,因为如果您的查询出现问题,catch
会立即触发返回false
。感谢@ilaijin表示如果出现问题就会抛出Exception
对象。
答案 0 :(得分:8)
通过查看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;
}
抛出异常(回滚后)如果失败或返回$result
,这是你回调的结果
答案 1 :(得分:0)
您还可以使用以下
DB::rollback();