Search code examples
phpmodellaravel-5relationshipcascading-deletes

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

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).


Solution

  • Try to use deleted instead of 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.