简体   繁体   中英

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

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.

Like already pointed out in the comments, you are performing the delete on a query builder instead of the actual related models. 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 .

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