Reputation: 4641
I have this (Postgres) query:
SELECT
p.*,
row_to_json(c.*) as "connection"
FROM connections c
INNER JOIN people p
ON p.id = c.connected_to_id
WHERE c.entity_id = 1
AND c.entity_table = 'releases'
AND c.connected_to_table = 'people'
Which returns rows like this:
[
{
id: 1,
name: 'Thom Yorke'
connection: {
id: 1,
type: 'vocal'
}
},
{
id: 1,
name: 'Thom Yorke'
connection: {
id: 2,
type: 'instrument'
}
}
]
In this case there are 2 rows in the connections table associated with Thom Yorke.
I'd like to achieve this data shape:
[
{
id: 1,
name: 'Thom Yorke'
connections: [
{
id: 1,
type: 'vocal'
},
{
id: 2,
type: 'instrument'
}
]
}
]
I'm struggling to find any examples (I'm not sure what terminology to search for!)
Thanks
Upvotes: 1
Views: 186
Reputation: 121754
Use json_agg()
in groups by people.id:
SELECT
p.*,
json_agg(row_to_json(c.*)) as "connections"
FROM connections c
INNER JOIN people p
ON p.id = c.connected_to_id
WHERE c.entity_id = 1
AND c.entity_table = 'releases'
AND c.connected_to_table = 'people'
GROUP BY p.id;
Upvotes: 1