find($userId); if (!$user) { return collect(); } $all = collect(); foreach ($user->roles as $role) { $all = $all->merge($role->resources); } $all = $all->merge($user->resources); return $all->unique('id')->values(); } /** * 构建目录/菜单树,节点包含权限与打开方式 */ // public function buildTree($resources, int $parentId = 0): array // { // $tree = []; // foreach ($resources as $node) { // if ($node->parent_id !== $parentId) continue; // // 子节点 // $children = []; // if ($node->type === 'directory') { // $children = $this->buildTree($resources, $node->id); // } // // 本级权限列表 // $authList = $resources // ->filter(fn($r) => $r->type === 'permission' && $r->parent_id === $node->id) // ->map(fn($r) => [ // 'id' => $r->id, // 'title' => $r->name, // 'auth_mark' => $r->code, // ])->values()->all(); // $tree[] = [ // 'id' => $node->id, // 'name' => $node->name, // 'path' => $node->url, // 'component' => $node->type === 'directory' ? 'Layout' : 'Page', // 'meta' => [ // 'title' => $node->name, // 'icon' => $node->icon, // 'keepAlive' => true, // 'authList' => $authList, // 'openType' => $node->open_type, // 'internal' | 'external' | 'iframe' // ], // 'children' => $children, // ]; // } // return $tree; // } /** * 构建目录/菜单树,节点包含权限与打开方式,并拼接完整路径到 component 字段 * @param \Illuminate\Support\Collection $resources * @param int $parentId * @param string $parentPath * @return array */ public function buildTree($resources, int $parentId = 0, string $parentPath = ''): array { $tree = []; foreach ($resources as $node) { if ($node->parent_id !== $parentId) continue; // 拼接完整路径 $currentPath = $parentPath; // 去掉结尾斜杠,防止重复 if ($currentPath && substr($currentPath, -1) === '/') { $currentPath = rtrim($currentPath, '/'); } // 子菜单的 path 不要补全斜杠 if (!empty($node->url)) { // 如果当前是根节点或父路径为空,直接用自身 if (!$currentPath) { $currentPath = $node->url; } else { // 防止 url 以 / 开头导致双斜杠 $url = ltrim($node->url, '/'); $currentPath = $currentPath . '/' . $url; } } // 子节点 $children = []; if ($node->type === 'directory') { $children = $this->buildTree($resources, $node->id, $currentPath); } // 权限 $authList = $resources ->filter(fn($r) => $r->type === 'permission' && $r->parent_id === $node->id) ->map(fn($r) => [ 'id' => $r->id, 'title' => $r->name, 'auth_mark' => $r->code, ])->values()->all(); $tree[] = [ 'id' => $node->id, 'name' => $node->name, 'path' => $node->url, 'component' => $currentPath, // 这里就是全路径 'meta' => [ 'title' => $node->name, 'icon' => $node->icon, 'keepAlive' => true, 'authList' => $authList, 'openType' => $node->open_type, ], 'children' => $children, ]; } return $tree; } /** * 获取用户所有权限code */ public function getPermissionCodes(int $userId): array { $resources = $this->getUserResources($userId); return $resources ->filter(fn($res) => $res->type === 'permission') ->pluck('code') ->unique() ->values() ->all(); } }