diff --git a/app/Traits/TreePath.php b/app/Traits/TreePath.php new file mode 100644 index 0000000..61aff97 --- /dev/null +++ b/app/Traits/TreePath.php @@ -0,0 +1,84 @@ +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) + { + return $q->where('path', 'like', '%-'.$pid.'-%'); + } + + public function scopeSort($q) + { + return $q->orderBy('parent_id')->orderBy('sort'); + } + + 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; + } +}