【发布时间】:2019-03-09 07:49:39
【问题描述】:
所以我有一篇文章,文章上有“cmets”..
评论允许人们回复..您可以回复回复..等等,这意味着最深的树根是N
表格外观的快速模型
Comments(id, news_id, user_id, body, likes)
Replies(id, parent_id) --> id here is = Comments.id
User(id, username, password)
News(id, title, body, image)
有没有办法查询 Postgres DB 给我类似的结果
因此,Replies 表中具有 null parent_id 的任何内容都是“主要”注释(也不是回复)。如果可能的话,我希望 children 字段在其内部填充(即回复回复)
Postgres 甚至可以做到这一点吗?还是我应该获取所有 Replies 和 Comments 加入它们,然后遍历每个试图找到合适的目的地?
顺便说一句,我使用 GoLang 作为我的后端,使用 Gorm 包来访问我的 postgres 数据库
编辑: 我正在使用这个查询
with recursive commentss as (
select r.id, r.parent, array[r.id] as all_parents,
c.body, u.username
from replies r
inner join comments c
on c.id = r.id
join users u
on u.id = c.user_refer
where (parent <> '') IS NOT TRUE
union all
select r.id, r.parent, c.all_parents || r.id,
co.body, u.username
from replies r
join comments co
on co.id = r.id
join users u
on u.id = co.user_refer
join commentss c
on r.parent = c.id
and r.id <> ALL (c.all_parents)
)
select * from commentss order by all_parents;
哪些结果:
这更接近了..但是我需要返回一个 JSON 对象,看起来像
comments: [
{
comment_id: ...,
username: ...,
comment_body: ....,
comment_likes: ....,
children: [...]
},
{
.....
}
]
comments 对象内的第一个项目将是不是回复的 cmets,children 字段应填充回复的 cmets.. 并且 children 内的 cmets 也应该有它们的children 填充到对该回复的回复
【问题讨论】:
-
样本数据和期望的结果真的很有帮助。
-
这取决于您的版本。研究 CTE,因为这种类型的递归查询正是您执行此查询的方式,前提是您的版本支持它们。
-
@Tomc 这是我使用 CTE 所能想到的最多的方法。有没有更好的方法来解决这个问题,或者 JSON 与 sql 是一个坏主意?
-
@GordonLinoff PING;这次修改更清楚了吗?
-
@MadoBaker 是的,但请提供一些我们可以复制的样本数据。所以我们可以写一个查询。否则我们必须编写它而无法检查它
标签: sql postgresql go go-gorm