I am trying to construct a query that returns an array of customer carts and all of their items, e.g.
Tables:
cart: id, customer_id
item: cart_id, price, brand
Desired JSON result example:
[{
"id": 1, "customer_id": 1,
"items": [{
"price": 14.50, "brand": "Coke"
}]
}]
Failing SQL Query (Testable here: http://sqlfiddle.com/#!17/0ef54/1):
SELECT jsonb_insert(to_jsonb(c.*), 'items', array(
SELECT to_jsonb(i.*)
FROM item i
WHERE i.cart_id = c.id
)
FROM cart c
How can one achieve this?