[英]I want to use Prisma to store nested comments (like on reddit). How can I retrieve all the nested comments?
我想要 model 嵌套评论,就像在 reddit 上一样。 我正在使用这样的一对多自我关系:
model Comment {
[...]
parentId String?
parent Comment? @relation("ParentChildren", fields: [parentId], references: [id])
children Comment[] @relation("ParentChildren")
}
所以每个孩子都通过parentId
连接到它的父母。 评论可以无限嵌套,父母可以有孙子,孙子等等。
我的问题是——是否可以在一个查询中检索所有父评论的后代? 我怎样才能做到这一点?
我的目标是得到一个 json object 看起来有点像这样:
{
comment: 'Lorem ipsum...',
children: [
{
comment: 'Lorem ipsum...',
children: [
{
comment: 'Lorem ipsum...',
children: []
},
{
comment: 'Lorem ipsum...',
children: []
},
],
},
],
},
model Comment {
id Int @id @default(autoincrement())
comment String
Children Comment[] @relation("Comment_Children")
parent Comment? @relation("Comment_Children", fields: [parent_id], references: [id])
parent_id Int?
}
let comment = await prisma.comment.findMany({
where: {
parent_id: null,
},
include: {
children: {
include: {
children: true,
},
},
},
});
let comment = await prisma.comment.create({
data: {
comment: req.body.comment,
parent_id: req.body.parent_id, // or `null` for parent comment
},
include: {
Children: {
include: {
Children: true,
},
},
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.