2017-01-23 65 views
0

我使用的是Postgres 9.6,並試圖建立一個Permissions模型允許Users訪問他們Projects及其Projects'Components。它看起來像這樣:通過中間模式返回嵌套的模型與SQL

用戶

+--------+--------+ 
| 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> 
    } 
    ] 
} 

projectsPermission模型確定和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的,它應該。

我會很感激如何得到它的返回有相關Permission和所有的components那些projects所有projects任何建議或指導。

回答

0

我能得到我需要像這樣的結構:

SELECT 
    u.id, 
    u.uuid, 
    ARRAY(
    SELECT 
     row_to_json(b.*) 
    FROM (
     SELECT 
     prj.id 
     FROM "Projects" prj 
     INNER JOIN "Permissions" prm 
     ON prj.id = prm.project_id 
     WHERE prm.user_id = u.id 
    ) b 
) as projects, 
    ARRAY(
    SELECT 
     row_to_json(c.*) 
    FROM (
     SELECT 
     cmp.id, 
     cmp.project_id 
     FROM "Components" cmp 
     INNER JOIN "Permissions" prm 
     ON cmp.project_id = prm.project_id 
     WHERE prm.user_id = u.id 
    ) c 
) as components 
FROM "Users" u 
WHERE u.uuid = ?