En PostgreSQL, puede construir el siguiente objeto JSON:
[
{ "name": "Portfolio #1", "cars": [ "Car #1", "Car #2" ] },
{ "name": "Portfolio #2", "cars": [ "Car #3" ] }
]
Podría construir el objeto a partir de sus tablas con la siguiente consulta:
select array_to_json(array(
select row_to_json(n)
from portfolio p
left join lateral (select p.name, array(select name from cars where portfolio_id = p.id) as cars) n on true
))
Y con cars.votes
campos incluidos:
select array_to_json(array(
select row_to_json(n)
from portfolio p
left join lateral (select p.id, p.name, array_to_json(array(
select row_to_json((select a from (select c.name, c.votes) a))
from cars c
where portfolio_id = p.id)) as cars) n on true
))