简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM