Search code examples
postgresqlnext.jsone-to-manydatabase-schemaprisma

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?


Solution

  • 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