简体   繁体   中英

Eloquent delete and MySQL foreign key cascade

I have these tables in MySQL database:

users['id', 'name'],

roles['id', 'title'] and

user_role ['user_id', 'role_id'] where both are foreign keys, CASCADE.


When it catches an exception the user remains in the table as wanted, while the row from the relation table is deleted.

try{
    $user->delete();
}
catch (\Exception $e){
    throw new \Dingo\Api\Exception\DeleteResourceFailedException('Error.');
}

Is this eloquent's mistake?


Now, I figured out a way to fix this but I'm not sure that it's the best practise. Is there a better way to do it?

try{
    $roleId = $user->roles[0]->id;
    $user->delete();
}
catch (\Exception $e){
    $user->roles()->attach($roleId);
    throw new \Dingo\Api\Exception\DeleteResourceFailedException('Error.');
}

If i understood your question, transactions are what you need.

Database Transactions

DB::transaction(function () {
    $user->delete();
});

and in case you face a deadlock use this one

 DB::transaction(function () {
    $user->delete();
},5);

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