如何在laravel中使用数据库事务? [英] How can I use db transaction in laravel?
本文介绍了如何在laravel中使用数据库事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试这个:
public function destroy($id)
{
DB::beginTransaction();
try {
$product = $this->product_repository->find($id);
$result = $product->categories()->detach();
if($result) {
list($status,$instance) = $this->product_repository->delete($id);
}
DB::commit();
return ['status'=>true,'data'=>$status];
} catch (\Exception $e) {
DB::rollback();
return ['status'=>false, 'message'=>$e->getMessage()];
}
}
如果执行了代码,则$this->product_repository->delete($id)
不起作用/未成功删除.
If the code executed, $this->product_repository->delete($id)
not work / not success delete.
但这是$product->categories()->detach();
,它可以正常工作/成功删除.
But this : $product->categories()->detach();
, it works / success deleted.
如果删除产品失败,删除类别也失败怎么办?
How to if delete product failed, delete category also failed?
推荐答案
您不能在transaction
内添加return
语句以终止整个过程并执行DB::rollback()
.
You can't add return
statement inside transaction
that halts entire process and DB::rollback()
is executed.
要切换return
,可以定义boolean
变量,并在catch
异常时创建false
.
To switch the return
, You can define a boolean
variable and make false
while you catch
exception.
赞:
public function destroy($id)
{
$success = true;
DB::beginTransaction();
try{
// Your Code
$product = $this->product_repository->find($id);
$result = $product->categories()->detach();
if($result) {
list($status,$instance) = $this->product_repository->delete($id);
}
DB::commit();
}catch(\Exception $e){
DB::rollback();
$success = false;
}
if($success){
// Return data for successful delete
}
else{
// Return data for unsuccessful delete
}
}
希望您能理解
这篇关于如何在laravel中使用数据库事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文