6

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: []
          },
        ],
      },
    ],
  },
lumenwrites
  • 1,287
  • 4
  • 18
  • 35
  • 1
    Unfortunately this isn't supported at the moment. The only possible workaround would be to implement it in SQL using `rawQuery`. There's an [issue](https://github.com/prisma/prisma/issues/3725) about it in the Prisma repo. I would suggest commenting your use-case over there so we can track the demand for this feature. – Tasin Ishmam Nov 25 '21 at 13:09
  • @TasinIshmam Thanks, will do! – lumenwrites Nov 25 '21 at 15:57
  • Here is the solutions using Prisma what you need: https://github.com/WebDevSimplified/nested-comments – Sebastian Korotkiewicz May 18 '23 at 06:25

1 Answers1

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