PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

PostgreSQL e nodejs/pg, restituiscono JSON nidificato

In PostgreSQL, puoi creare il seguente oggetto JSON:

[
    { "name": "Portfolio #1", "cars": [ "Car #1", "Car #2" ] },
    { "name": "Portfolio #2", "cars": [ "Car #3" ] }
]

Puoi costruire l'oggetto dalle tue tabelle con la seguente query:

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
  ))

E con cars.votes campi inclusi:

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
  ))