LARAVEL : SoftDelete all childs and their childs On SoftDelete a parent

LARAVEL : SoftDelete all childs and their childs On SoftDelete a parent

我正在尝试根据 parent_id 方法用一个 sql table 制作一个动态树视图菜单。

我可以在我的 blade 页面上生成树视图并添加新的部分和子部分。

我现在的问题是如何在软删除 parent 部分时软删除所有子项和子项?

例如删除 PHP 部分时,必须删除 PHP 部分下的所有子项和子项。

谢谢。

您可以利用 Laravel 提供的活动。

<?php

class Parent extends Model
{

    protected static function boot()
    {
        static::deleting(function ($instance) {
            $instance->child->each->delete();
        });

        static::restoring(function ($instance) {
            $instance->child->each->restore();
        });
    }
}

然后你在 child class 中做同样的事情。当您的 $parent 被软删除时,它将软删除所有 child。然后 child 也将软删除所有它的 child.

更多信息:https://laravel.com/docs/5.7/eloquent#events