PostgreSQL 和 nodejs/pg、return 嵌套 JSON

PostgreSQL and nodejs/pg, return nested JSON

我将 PostgreSQL 与 nodejs 和 pg 一起使用。 一切正常,但我想将 PostgreSQL 的结果输出为嵌套 json - 就好像我正在使用 MongoDB 或类似的。

我来自 PostgreSQL 的 2 个表是:

portfolio (id int, name text)

cars (portfolio_id int, name text);

是否有 "correct" 方法返回具有以下结构的 JSON 对象:

{
    { name: 'Portfolio #1', cars: { name: 'Car #1', name: 'Car #2' },
    { name: 'Portfolio #2', cars: { name: 'Car #3' }
}

我在nodejs/pg查询数据库的一般方式是:

client.query('SELECT ...', [params], function(err, result) {
    done();
    if (err) {
        res.status(500).json({ error: err });
    } else {
        res.json({ portfolios: result.rows });
    }
});

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