Laravel: Using try...catch with DB::transaction()(Laravel:在 DB::transaction() 中使用 try...catch)
问题描述
我们都使用 DB::transaction() 进行多个插入查询.这样做时,应该将 try...catch 放在里面还是包装它?如果出现问题,事务将自动失败,是否还需要包含 try...catch ?
We all use DB::transaction() for multiple insert queries. In doing so, should a try...catch be placed inside it or wrapping it? Is it even necessary to include a try...catch when a transaction will automatically fail if something goes wrong?
示例 try...catch 包装交易:
// try...catch
try {
// Transaction
$exception = DB::transaction(function() {
// Do your SQL here
});
if(is_null($exception)) {
return true;
} else {
throw new Exception;
}
}
catch(Exception $e) {
return false;
}
相反,一个 DB::transaction() 包装了一个 try...catch:
The opposite, a DB::transaction() wrapping a try...catch:
// Transaction
$exception = DB::transaction(function() {
// try...catch
try {
// Do your SQL here
}
catch(Exception $e) {
return $e;
}
});
return is_null($exception) ? true : false;
或者只是一个没有 try...catch 的事务
Or simply a transaction w/o a try...catch
// Transaction only
$exception = DB::transaction(function() {
// Do your SQL here
});
return is_null($exception) ? true : false;
推荐答案
如果您需要通过代码手动退出"事务(无论是通过异常还是只是检查错误状态),您不应该使用 DB::transaction() 而是将您的代码包装在 DB::beginTransaction 和 DB::commit/DB::rollback():
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (Exception $e) {
DB::rollback();
// something went wrong
}
请参阅交易文档.
这篇关于Laravel:在 DB::transaction() 中使用 try...catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel:在 DB::transaction() 中使用 try...catch
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
