How can I use db transaction in laravel?

2019-02-15 16:44发布

问题:

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?

回答1:

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.



回答2:

You can use it like this:

$returnResult = [];

DB::beginTransaction();

try {

    ...

    DB::commit();

    $returnResult['status'] = true;
    $returnResult['data'] = $status;
} catch (...) {

    ...

    DB::rollback();

    $returnResult['status'] = true;
    $returnResult['message'] = $e->getMessage();
}

return $returnResult;