繁体   English   中英

PostgreSQL 和 nodejs/pg,返回嵌套的 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);

是否有返回具有以下结构的 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
  ))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM