【问题标题】:Querying sub-sub table in Supabase / Grandchild relationship in JOIN QUERY在 JOIN QUERY 中查询 Supabase / Grandchild 关系中的子子表
【发布时间】:2023-02-10 22:05:26
【问题描述】:

给定以下架构:

CREATE TABLE organization (
   org_name text  NOT NULL,
   PRIMARY KEY (org_name)
);

CREATE TABLE teams (
   org_name text NOT NULL,
   team_name text NOT NULL,
   PRIMARY KEY (org_name, team_name),
   FOREIGN KEY (org_name)
      REFERENCES organization (org_name)
);

CREATE TABLE projects (
   org_name text NOT NULL,
   team_name text NOT NULL,
   project_name text NOT NULL,
   products jsonb,
   PRIMARY KEY (org_name, team_name, project_name),
   FOREIGN KEY (org_name)
      REFERENCES organization (org_name),
   FOREIGN KEY (org_name, team_name)
      REFERENCES teams (org_name, team_name)
);

我想查询 teams 表,但也从 projects 表返回 products。有没有办法做到这一点?

【问题讨论】:

    标签: javascript postgresql supabase supabase-database postgrest


    【解决方案1】:

    对于单个关系集,则可以执行以下操作(假设上下关系为:

    organization -> teamsteams -> projects

    const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
    const { data: ret, error } = await supabase
      .from('organization')
      .select(`*, 
               teams(*,
                     projects(products)
                    )
              `);
    console.log(JSON.stringify(ret));
    

    在这种情况下,这是不可能的,您会收到以下错误:

    无法嵌入,因为为“组织”和“团队”找到了不止一种关系

    在这种情况下,您可以在调用 supabase 时选择关系: teams!projectsteams!teams_org_name_fkey。大多数情况下首选前者。

    const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
    const { data: ret, error } = await supabase
      .from('organization')
      .select(`*, 
              teams!projects(*,
                            projects(products)
                            )
             `);
    

    输出:

    [{"org_name":"Contoso","teams":[{"org_name":"Contoso","team_name":"Contoso Café","projects":[{"products":{"Dairy":"latte ","coffee":["french press","expresso","cold brew"]}}]}]}]

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      相关资源
      最近更新 更多