bump
Jul 9, 2016
12
Level 13
laravel 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
public function checks()
{
return $this->hasMany('App\CheckProcedure');
}
public function results()
{
return $this->hasMany('App\CheckResult');
}
protected static function boot(){
parent::boot();
static::deleted(function($check)
{
foreach($check->checks as $check_object_check) {
$check_object_check->delete();
}
foreach($check->results as $check_object_result) {
$check_object_result->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).
Please or to participate in this conversation.