parent_id) { $parent = static::query()->findOrFail($model->parent_id); $model->path = $parent->path . $parent->id . '-'; } else { $model->parent_id = 0; $model->path = '-'; } }); static::updating(function (Model $model) { if ($model->parent_id) { $parent = static::query()->findOrFail($model->parent_id); $model->path = $parent->path . $parent->id . '-'; } else { $model->parent_id = 0; $model->path = '-'; } }); static::deleting(function (Model $model) { static::query()->allChildren($model->id)->delete(); }); } protected function parentIds(): Attribute { return Attribute::make( get: fn () => explode('-', substr($this->path, 1, -1)), ); } public function children() { return $this->hasMany(static::class, 'parent_id'); } public function parent() { return $this->belongsTo(static::class, 'parent_id'); } public function scopeAllChildren($q, $pid) { $q->where('path', 'like', '%-'.$pid.'-%'); } public function scopeSort($q) { $q->orderBy('parent_id', 'asc')->orderBy('sort', 'asc'); } public static function getTreeList($list, $pid = 0) { $tree = collect(); foreach ($list->where('parent_id', $pid)->all() as $item) { $item->children = []; $children = $list->where('parent_id', $item->id); if ($children->count() > 0) { $item->children = static::getTreeList($list, $item->id); } $tree->push($item); } return $tree; } }