PostgreSQLでは、次のJSONオブジェクトを作成できます。
[
{ "name": "Portfolio #1", "cars": [ "Car #1", "Car #2" ] },
{ "name": "Portfolio #2", "cars": [ "Car #3" ] }
]
次のクエリを使用して、テーブルからオブジェクトを作成できます。
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
))
そしてcars.votes
で 含まれるフィールド:
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
))