hasMany(SiteAlbumFolder::class, 'parent_id'); } // 递归构建父子关系树 public static function buildTree(Collection $folders, $parentId = null) { return $folders ->where('parent_id', $parentId) // 过滤出当前层级的文件夹 ->sortByDesc('order') // 按顺序排序 ->map(function ($folder) use ($folders) { // 递归获取子文件夹 $folder->children = self::buildTree($folders, $folder->id); return [ 'id' => $folder->id, 'title' => $folder->title, 'parent_id' => $folder->parent_id, 'order' => $folder->order, 'folder_type' => $folder->folder_type, 'show_tabs' => $folder->show_tabs, 'enabled' => $folder->enabled, 'created_at' => $folder->created_at, 'updated_at' => $folder->updated_at, 'cover' => $folder->cover, 'children' => $folder->children->values()->toArray(), // 子文件夹数据 ]; }) ->values(); // 重置键名 } // public static function getfolderTreeIds($title) { // 获取所有文件夹记录并预加载子级 $folders = self::with('children')->get()->toArray(); $ids = []; // 递归遍历查找目标标题的节点及其子节点 array_walk($folders, function ($folder) use ($title, &$ids) { if ($folder['title'] == $title) { self::collectIdsRecursive($folder, $ids); } }); return array_unique($ids); // 去重后返回 } /** * 递归收集节点及其子节点ID */ protected static function collectIdsRecursive($node, &$ids) { $ids[] = $node['id']; if (!empty($node['children'])) { array_walk($node['children'], function ($child) use (&$ids) { self::collectIdsRecursive($child, $ids); }); } } }