MenuType::class, 'visible' => 'integer', 'status' => 'integer', ]; public function children(): HasMany { return $this->hasMany(self::class, 'parent_id'); } public function childrenRecursive(): HasMany { return $this->children()->with('childrenRecursive')->orderBy('sort'); } /** * 获取完整菜单树 */ public static function tree(): array { $all = self::where('status', 1)->orderBy('sort')->get()->toArray(); return self::buildTree($all); } private static function buildTree(array $items, int $parentId = 0): array { $tree = []; foreach ($items as $item) { if ($item['parent_id'] == $parentId) { $children = self::buildTree($items, $item['id']); if ($children) { $item['children'] = $children; } $tree[] = $item; } } return $tree; } }