我想对嵌套评论进行建模,就像在 reddit 上一样。我正在使用这样的一对多自关系:
model Comment {
[...]
parentId String?
parent Comment? @relation("ParentChildren", fields: [parentId], references: [id])
children Comment[] @relation("ParentChildren")
}
Run Code Online (Sandbox Code Playgroud)
所以每个孩子都通过 与其父母相连parentId。评论可以无限嵌套,父母可以有孙子、孙子等等。
我的问题是 - 是否可以在一个查询中检索父评论的所有后代?我怎样才能做到这一点?
我的目标是获得一个看起来像这样的 json 对象:
{
comment: 'Lorem ipsum...',
children: [
{
comment: 'Lorem ipsum...',
children: [
{
comment: 'Lorem ipsum...',
children: []
},
{
comment: 'Lorem ipsum...',
children: []
},
],
},
],
},
Run Code Online (Sandbox Code Playgroud)
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?
}
Run Code Online (Sandbox Code Playgroud)
let comment = await prisma.comment.findMany({
where: {
parent_id: null,
},
include: {
children: {
include: {
children: true,
},
},
},
});
Run Code Online (Sandbox Code Playgroud)
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,
},
},
},
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1576 次 |
| 最近记录: |