使用SQL通过中间模型返回嵌套模型

时间:2017-01-23 20:12:17

标签: sql postgresql

我正在使用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}}的建议或指导。

1 个答案:

答案 0 :(得分:0)

我能够得到我需要的结构:

;