select jsonb_agg(to_jsonb(c.*) ||
jsonb_build_object
(
'items',
(select jsonb_agg(to_jsonb(i.*) - 'cart_id') from item i where c.id = i.cart_id)
)
) from cart c;
create temporary table item (cart_id integer, price numeric, brand text);
create temporary table cart (id integer, customer_id integer);
insert into item values (1, 10, 'skoda'),(1, 11, 'ford'), (1, 12, 'opel');
insert into item values (2, 20, 'skoda'),(2, 21, 'ford'), (2, 22, 'opel');
insert into cart values (1, 1), (2, 2);
select jsonb_agg(to_jsonb(c.*) || jsonb_build_object(
'items', (select jsonb_agg(to_jsonb(i.*) - 'cart_id') from item i where c.id = i.cart_id)
)) from cart c;
[
{
"id": 1,
"items": [
{
"brand": "skoda",
"price": 10
},
{
"brand": "ford",
"price": 11
},
{
"brand": "opel",
"price": 12
}
],
"customer_id": 1
},
{
"id": 2,
"items": [
{
"brand": "skoda",
"price": 20
},
{
"brand": "ford",
"price": 21
},
{
"brand": "opel",
"price": 22
}
],
"customer_id": 2
}
]