[英]Eloquent delete and MySQL foreign key cascade
I have these tables in MySQL database: 我在MySQL数据库中有这些表:
users['id', 'name'], users ['id','name'],
roles['id', 'title'] and 角色['id','标题']和
user_role ['user_id', 'role_id'] where both are foreign keys, CASCADE. user_role ['user_id','role_id']其中两个都是外键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. 如果我理解您的问题,那么交易就是您所需要的。
DB::transaction(function () {
$user->delete();
});
and in case you face a deadlock use this one 如果您遇到僵局,请使用此
DB::transaction(function () {
$user->delete();
},5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.