【发布时间】:2016-12-12 01:33:28
【问题描述】:
我将从顶部开始...我有两个表,引号和 cmets。一句话“有很多” cmets。我的最终目标是在前端有两个 .map() 函数,一个将所有引号呈现到我的页面,另一个呈现位于其上方的引号的每个评论。
我正在尝试从 psql 中检索一个返回如下内容的 json:
[
{
"id": 1,
"content": "quote number 1!",
"name": null,
"num_of_flags": null,
"comments": [
{
"id": 1,
"comment_content": "comment one!",
"num_of_likes": null,
"quote_id": 1
},
{
"id": 1,
"comment_content": "comment 2!",
"num_of_likes": null,
"quote_id": 1
}
]
这样,'quotes' 是一个对象数组,属于它的 cmets 也是。
这是我真正得到的结果:
[
{
"id": 1,
"content": "quote number 1!",
"name": null,
"num_of_flags": null,
"comments": [
{
"id": 1,
"comment_content": "comment 1!",
"num_of_likes": null,
"quote_id": 1
}
]
},
{
"id": 2,
"content": "quote number 2!",
"name": null,
"num_of_flags": null,
"comments": [
{
"id": 2,
"comment_content": "comment 2!",
"num_of_likes": null,
"quote_id": 2
}
]
},
{
"id": 3,
"content": "quote number 3!",
"name": null,
"num_of_flags": null,
"comments": [
{
"id": 3,
"comment_content": "comment 3",
"num_of_likes": null,
"quote_id": 1
}
]
}
]
注意第三个'quote'对象。它包含“评论 3”。评论 3 的 quote_id 为 1,而 quote_id 是一个外键,应该只与引用编号 1 相关,因此它不应该出现在引用对象 3 中。此外,我的数据库实际上包含所有这些的多个 cmets引号,但我的 json 只返回一条评论,它甚至与引号没有正确的关系。
这是我的架构:
BEGIN;
DROP TABLE IF EXISTS quotes;
DROP TABLE IF EXISTS comments;
CREATE TABLE quotes (
id SERIAL PRIMARY KEY,
name VARCHAR,
content VARCHAR,
num_of_flags INTEGER
);
CREATE TABLE comments (
id SERIAL PRIMARY KEY,
comment_content VARCHAR,
num_of_likes INTEGER,
quote_id INTEGER
);
ALTER TABLE ONLY comments
ADD CONSTRAINT quotes_id_fkey
FOREIGN KEY (quote_id)
REFERENCES quotes(id);
COMMIT;
我查看了这个blog 并了解了一些关于 json_agg 聚合函数的知识,并且能够拼凑一个 psql 调用,它确实将我的“cmets”变成了一个数组(正如你在我的第二个代码块中看到的那样这个帖子)。这是 psql 调用:
SELECT
q.id,
q.content,
q.name,
q.num_of_flags,
json_agg(c.*) as comments
FROM quotes q
INNER JOIN comments c USING (id)
GROUP BY q.id, q.content, q.name, q.num_of_flags
我认为关键是调整 psql 调用,但我似乎无法做出正确的调整。我还尝试应用横向连接,以及我在this Stack Overflow 帖子中找到的 array_to_json 方法,但无法将它们应用到我的项目中,可能是因为我的语法。
希望这篇文章清晰易懂!如果您碰巧遇到并可以帮助我,我真的很感激您的时间。
-比尔
【问题讨论】:
标签: json postgresql multidimensional-array