简体   繁体   中英

How can I use db transaction in laravel?

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?

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM