0

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}]
1
  • Please fix your example: In your query you have "Multi Role" at the column of "first_name". I think this is not correct, isn't it? Commented Oct 27, 2018 at 7:12

1 Answer 1

3

demo: db<>fiddle

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
  1. Create a json object with jsonb_build_object, Postgres JSON functions
  2. Aggregate the json objects with jsonb_agg, Postgres aggregate functions

Of course you can use type json instead of jsonb as well; Postgres JSON types

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.