Prisma self relation to display related posts

Viewed 166

I am trying to create a prisma schema for a self relation. I would like to be able to show related posts for each post. Here is my post model:

model Post {
  id                 Int  @id @default(autoincrement())
  title              String
  content            String
  relatedPosts       Post[]
}

I am unsure on how to get this to work, the error message I am getting says that I need to define the other side of the relationship.

1 Answers

You are trying to create a many-to-many self relation. In such cases, you need to create two fields:

  1. One field to represent the suggested posts for a given parent post (named relatedPosts in the example)
  2. One field to represent the parent for a given suggested post (named relatedPostParent in the example)

This is what the syntax will look like

model Post {
  id                Int    @id @default(autoincrement())
  title             String
  content           String
  relatedPosts      Post[] @relation("RelatedPosts", references: [id])   // child post (post that are suggested)
  relatedPostParent Post[] @relation("RelatedPosts", references: [id])   // parent post (parent post of a suggested post)
}

Note that this is an implicit many-to-many relation. The article linked at the top also shows how to create an explicit many-to-many relation, if that is what you'd prefer.

Related