Prisma Schema and query for comments and comment thats a replay to a comment in single table

42 Views Asked by At

I have a basic chat system with user comments, and I am now adding a reply method but not able to create in a self relationship I think is possible.

    model shoutMessage {
      id        String          @id @default(cuid())
      createdAt DateTime        @default(now())
      message   String
      authorId  String
      type      Int
      parent    String?
      like      Int             @default(0)
      author    User            @relation(fields: [authorId], references: [id], onDelete: Cascade)
      likes     tb_pbot_shout[]
      root   shoutMessage? @relation("replied", fields: [parent], references: [id], onDelete: Cascade)
  replies     shoutMessage[] @relation("replied")
    }

basic comments then I have added a parentId to mark as a reply of course. I thought I could create a relationship to itself but not able to get it to function. Then Thinking ahead I asume the relation will be enough to do the entire tree in a single query as

const shouts = prisma.shoutMessage.findMany({
  select: { id,true,
  .... replies, true,
}
});

I believe the schema is correct, when I add a replay i get the following error that does not makes sense, and if i add a new root comment that does not have a parent then it works as expected?

here is the error

Invalid `prisma.shoutMessage.create()` invocation:

{
  data: {
    author: {
      connect: {
        id: "cltna90na0002r4wz7dktapnp"
      }
    },
    message: "<p>asdasdasdasdasd</p>",
    parent: "cltw3r6uy0001md3c0lrnfbla",
    ~~~~~~
    type: 1,
?   id?: String,
?   createdAt?: DateTime,
?   like?: Int,
?   likes?: tb_pbot_shoutCreateNestedManyWithoutShoutInput,
?   root?: shoutMessageCreateNestedOneWithoutReplyInput,
?   reply?: shoutMessageCreateNestedManyWithoutRootInput
  }
}

Unknown argument `parent`. Available options are marked with ?.
    at async replyShout (./app/chat2/_lib/process.tsx:272:22)
    at async $$ACTION_2 (./app/chat2/page.tsx:173:5)
digest: "1873872561"

Soluition, must add as root and then connect the parent.

 let newComment = await prisma.shoutMessage.create({
  
    data: {
      author: { connect: { id: user?.id } },
      message: message,
      root: { connect: { id: messageId } },
      type: type,
    },
  });
1

There are 1 best solutions below

0
Radium Chris On

Can not simply add the parent, must connect the reply to the parent as such

  let newComment = await prisma.shoutMessage.create({
    data: {
      author: { connect: { id: user?.id } },
      message: message,
      root: { connect: { id: messageId } },
      type: type,
    },
  });