简体   繁体   中英

I want to use Prisma to store nested comments (like on reddit). How can I retrieve all the nested comments?

I want to model nested comments, like on reddit. I'm using a one-to-many self relation like this:

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

So each child is connected to its parent by parentId . The comments can be infinitely nested, parents can have grand-children, grand-grand-children, and so on.

My question is - is it possible to retrieve all of the parent comment's descendants in one query? How can I do that?

My goal is to get a json object that looks kinda like this:

  {
    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,
      },
    },
  },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM