【问题标题】:I want to use Prisma to store nested comments (like on reddit). How can I retrieve all the nested comments?我想使用 Prisma 来存储嵌套评论(比如在 reddit 上)。如何检索所有嵌套评论?
【发布时间】:2022-04-16 12:16:04
【问题描述】:

我想为嵌套的 cmets 建模,例如在 reddit 上。我正在使用这样的一对多自我关系:

model Comment {
  [...]
  parentId String?
  parent Comment? @relation("ParentChildren", fields: [parentId], references: [id])
  children Comment[] @relation("ParentChildren")
}

所以每个孩子都通过parentId 连接到其父母。 cmets可以无限嵌套,父母可以有孙子,孙子,等等。

我的问题是 - 是否可以在一个查询中检索所有父评论的后代?我该怎么做?

我的目标是得到一个看起来像这样的 json 对象:

  {
    comment: 'Lorem ipsum...',
    children: [
      {
        comment: 'Lorem ipsum...',
        children: [
          {
            comment: 'Lorem ipsum...',
            children: []
          },
          {
            comment: 'Lorem ipsum...',
            children: []
          },
        ],
      },
    ],
  },

【问题讨论】:

  • 很遗憾,目前不支持此功能。唯一可能的解决方法是使用rawQuery 在SQL 中实现它。在 Prisma 存储库中有一个关于它的 issue。我建议您在那里评论您的用例,以便我们跟踪对该功能的需求。
  • @TasinIshmam 谢谢,会的!

标签: prisma prisma2


【解决方案1】:
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,
      },
    },
  },
});

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2014-08-28
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多