我正在使用Postgres 9.6并尝试设置Permissions
模型,以允许Users
访问他们的Projects
及其Projects
'Components
。它看起来像这样:
用户
+--------+--------+
| id | uuid |
+--------+--------+
权限
+--------+-----------+--------------+
| id | user_id | project_id |
+--------+-----------+--------------+
项目
+--------+
| id |
+--------+
组件
+--------+--------------+
| id | project_id |
+--------+--------------+
我希望User
uuid的查询返回以下格式:
{
id: <user.id>,
uuid: <user.uuid>,
projects: [
{
id: <project1.id>
},
{
id: <project2.id>
}
],
components: [
{
id: <component1.id>,
project_id: <project1.id>
},
{
id: <component2.id>,
project_id: <project2.id>
},
{
id: <component3.id>,
project_id: <project1.id>
}
]
}
projects
模型确定Permission
的位置components
属于projects
的所有组件。
到目前为止,我已经尝试了
SELECT
u.id,
u.uuid,
ARRAY(
SELECT row_to_json(pr.*)
FROM (
SELECT
proj.id
FROM "Projects" AS proj
WHERE proj.id = p.project_id
) pr
) AS projects,
ARRAY(
SELECT row_to_json(cm.*)
FROM (
SELECT
comp.id,
comp.project_id
FROM "Components" AS comp
WHERE comp.project_id = p.project_id
) cm
) AS components
FROM "Users" u INNER JOIN "Permissions" p
ON u.id = p.user_id
WHERE u.uuid = ?
这很接近,但它不会返回它应该的所有projects
和所有components
。
我很感激有任何关于如何让它返回所有projects
Permission
以及所有components
projects
的{{1}}的建议或指导。
答案 0 :(得分:0)
我能够得到我需要的结构:
;