Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 与postgres数组字段的内部联接_Ruby On Rails_Postgresql_Jsonb - Fatal编程技术网

Ruby on rails 与postgres数组字段的内部联接

Ruby on rails 与postgres数组字段的内部联接,ruby-on-rails,postgresql,jsonb,Ruby On Rails,Postgresql,Jsonb,我们有一个使用rails、react和postgresql的CMS。我们的桌子里有书页和书页。 每个页面由一组片段(一个数组字段)组成 我们有可以跨多个页面使用的片段 假设我们正在呈现页面id50806。我们的react前端需要以下格式的数据 pieces: [ {id: B1fu5jthb, included_on_pages: [50808, 50806]}, {id: BJTNssF2Z, included_on_pages: [50808]} ] 因此,目前,为了在页面上查找包含

我们有一个使用rails、react和postgresql的CMS。我们的桌子里有书页和书页。 每个页面由一组片段(一个数组字段)组成

我们有可以跨多个页面使用的片段

假设我们正在呈现页面id
50806
。我们的react前端需要以下格式的数据

pieces: [
 {id: B1fu5jthb, included_on_pages: [50808, 50806]},
 {id: BJTNssF2Z, included_on_pages: [50808]}
]
因此,目前,为了在页面上查找包含的
,我正在编写一个查询,以获取页面的所有部分,然后在每个部分上循环查找包含特定部分的页面

(基本上是N+1个查询)。

从页面id=50806的页面片段中选择片段

在每个部件上循环

从页面片段中选择页面id,其中“B1fu5jthb”=any(页面片段.片段)

所以我的问题,,
我们可以编写一个
join语句
来获取所有片段及其
包含在页面上的
而不是在每个片段上循环查找其包含的页面,我认为将unesting、
任何
比较和数组聚合结合起来应该可以工作:

with
  pcs as (select unnest(pieces) as id from page_pieces where page_id = 50806)
select id, array_agg(page_id) as included_on_pages
from pcs inner join page_pieces on id = any(pieces)
group by id;

我认为不测试、
任何
比较和数组聚合的组合应该可以工作:

with
  pcs as (select unnest(pieces) as id from page_pieces where page_id = 50806)
select id, array_agg(page_id) as included_on_pages
from pcs inner join page_pieces on id = any(pieces)
group by id;