我有三个表(PostgreSQL):
ModelA:
model_a_id
item1
item2
ModelB:
model_b_id
item1
item2
ModelA_ModelB:
model_a_id foreign_key to ModelA
model_b_id foreign_key to ModelB
好
我想选择与ModelB有所有关系的All ModelA。
我想要的是:
[{
Record1ModelA: {
item1: 'A',
item2: 'B',
modelBList: [{
Record1ModelB: {
item1: 'C',
item2: 'D'
},
Record2ModelB: {
item1: 'E',
item2: 'F'
}
...
}]
},
Record2ModelA: {
item1: 'G',
item2: 'H',
modelBList: [{
Record1ModelB: {
item1: 'I',
item2: 'G'
},
Record2ModelB: {
item1: 'K',
item2: 'L'
}
...
}]
}
...
}]
问题:
答案 0 :(得分:0)
好的,最后,我找到了这个问题的答案:
答案是:json_agg
in postgresql
SELECT ModelA.model_a_id, ModelA.item1, ModelA.item2, json_agg(mb.*)
FROM ModelA
LEFT JOIN ModelA_ModelB as mab on ModelA.model_a_id = mab.model_a_id
LEFT JOIN ModelB as mb on mb.model_b_id = mab.model_b_id
GROUP BY ModelA.model_a_id