duanlangwen9597 2017-07-20 23:39
浏览 588
已采纳

如何在laravel中使用db transaction?

I try this :

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()];
    }
}

If the code executed, $this->product_repository->delete($id) not work / not success delete.

But this : $product->categories()->detach();, it works / success deleted.

How to if delete product failed, delete category also failed?

  • 写回答

2条回答 默认 最新

  • dongpao1926 2017-07-20 23:42
    关注

    You can't add return statement inside transaction that halts entire process and DB::rollback() is executed.

    To switch the return, You can define a boolean variable and make false while you catch exception.

    Like this:

    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
        }
    }
    

    Hope you understand.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部