Reputation: 2104
I have a many to many relationship between users and roles table (A typical usecase). They are related together using a user_role table. I execute the below query:
select
u.id, u.first_name, u.last_name, u.middle_name,
u.email_address, r.id, r.role_code
from
master.user u
left join
master.user_role ur
on ur.user_id = u.id
and ur.is_void = false
left join
master.role r
on r.id = ur.role_id
and r.is_void = false
where u.id = 7 and u.is_void = false
This results to
7;"Multi Role";"First";"Middle";"[email protected]";1;"ST"
7;"Multi Role";"First";"Middle";"[email protected]";2;"TC"
How do I aggregate the roles into one json or array column, such that it results to :
7;"Multi Role";"First";"Middle";"[email protected]";[{id: 1, role_code : ST}, {id: 2, role_code: TC}]
Upvotes: 0
Views: 192
Reputation: 23676
SELECT
id,
first_name,
last_name,
middle_name,
email_address,
jsonb_agg(
jsonb_build_object('id', r_id, 'role_code', role_code)
)
FROM
result_table
GROUP BY id, first_name, last_name, middle_name, email_address
jsonb_build_object
, Postgres JSON functionsjsonb_agg
, Postgres aggregate functionsOf course you can use type json
instead of jsonb
as well; Postgres JSON types
Upvotes: 3