将嵌套的JSON从多个到多个从PostgreSQL连接到Node.js的表中返回

任何人都可以帮助我查询postgres中的许多关系表吗?

我有桌子:

> 1.exercise(id,name) > 2.tag(id,label) > 3.tag_in_exercise(id,exercise_id,tag_id) 

比方说,我们有一个练习通过tag_in_exercise绑定了两个标签

当使用查询时:

 select e.id,t.label from exercise e left join tag_in_exercise te on e.id=te.exercise_id left join tag t on te.tag_id=t.id 

我会收到JSON

 [ { id: 1, label: 'basic1' }, { id: 1, label: 'basic2' }] 

但我想收到它作为嵌套的JSON

 [ { id: 1, tags:[ {'basic1'},{'basic2'} ] }] 

是否有可能通过使用standat postgresql查询或我需要使用一些ORM?

或者如果存在另一个解决scheme,请让我知道,

谢谢

PostgreSQL不会返回您发布的JavaScript对象。 您的节点驱动程序正在转换由PostgreSQL返回的数组,该驱动程序将转换为JavaScript对象。

但是,您可以让PostgreSQL返回一个我怀疑将会通过使用array_agg来转换的结构。

尝试这个:

SELECT e.id,array_agg(t.label) AS label FROM exercise e LEFT JOIN tag_in_exercise te on e.id=te.exercise_id LEFT JOIN tag t on te.tag_id=t.id GROUP BY e.id;

你会得到一个原始的PostgreSQL结果在你想要的结构,希望司机将翻译,你打算:

id | label
----+----------------- 1 | {basic1,basic2} 2 | {NULL}