Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prisma model self-referencing (one to many)

I want to create an schema where an entity Chapter has children that are also Chapter.

It has to be a relation one to many since one chapter can have many children but only one parent.

I'm finding it difficult to define it in my Prisma schema. I have tried some approaches but always show an error:

// children and parent fields
model Chapter {
  id          Int       @default(autoincrement()) @id
  // ...
  children    Chapter[] @relation("children")
  parent      Chapter?  @relation(fields: [parentId], references: [id])
  parentId    Int?
}

// children field whith @relation
model Chapter {
  id          Int       @default(autoincrement()) @id
  // ...
  children    Chapter[] @relation("children")
}

// just children as an array of Chapter
model Chapter {
  id          Int       @default(autoincrement()) @id
  // ...
  children    Chapter[]
}

// Only parent (I could work with that)
model Chapter {
  id          Int       @default(autoincrement()) @id
  // ...
  parent      Chapter?  @relation(fields: [parentId], references: [id])
  parentId    Int?
}

Any ideas?

like image 937
user2289947 Avatar asked Oct 21 '25 16:10

user2289947


1 Answers

This one is the way to go. A 1-many relation where a parent can have multiple chapters:

model Chapter {
  id       Int       @id @default(autoincrement())
  children Chapter[] @relation("children")
  parent   Chapter?  @relation("children", fields: [parentId], references: [id])
  parentId Int?      @map("chapterId")
}

We also have this in the docs: https://www.prisma.io/docs/concepts/components/prisma-schema/relations/self-relations#one-to-many-self-relations

like image 131
Ryan Avatar answered Oct 23 '25 08:10

Ryan