[英]laravel5.2 delete model with all relations
My current model has some relations.我现在的模型有一些关系。 How can I delete them too, in case of model will be deleted?如果模型将被删除,我该如何删除它们? This query won't delete the related models, only the 'main model'.此查询不会删除相关模型,只会删除“主模型”。
I use this code to call:我使用此代码调用:
$checks = Check::where('created_at','<=', Carbon::now()
->subHours(3))
->with('checks')
->with('results')
->delete();
Here's my current model of Check这是我当前的 Check 模型
protected static function boot(){
parent::boot();
static::deleting(function($check) {
$check->checks()->delete();
$check->results()->delete();
});
}
Results and checks contain more than one entry for each check.结果和检查包含每个检查的多个条目。 Meaning this to make things clear:这意味着使事情清楚:
One check may have n CheckResult
and may have n CheckProcedure
(I'll of course delete all of them too).一张支票可能有 n 个CheckResult
,也可能有 n 个CheckProcedure
(我当然也会删除所有这些)。
Try to use deleted
instead of deleting
:尝试使用deleted
而不是deleting
:
protected static function boot(){
parent::boot();
static::deleted(function($check)
{
$check->checks()->delete();
$check->results()->delete();
});
}
Also try to parse object by object from returned collection:还尝试从返回的集合中逐个解析对象:
foreach($check->checks as $check_object) {
$check_object->delete();
}
Hope this helps.希望这可以帮助。
Like already pointed out in the comments, you are performing the delete on a query builder instead of the actual related models.就像评论中已经指出的那样,您正在查询构建器而不是实际相关模型上执行删除。 ie IE
You should have你应该有
$check->checks->delete();
$check->results->delete();
instead of what you currently have.而不是你目前拥有的。
In addition, the right way to do this assuming you are using a relational database is to use foreign keys with cascade delete action .此外,假设您使用的是关系数据库,正确的做法是使用外键和级联删除操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.