【问题标题】:Prisma model self-referencing (one to many)Prisma 模型自引用(一对多)
【发布时间】:2021-10-20 18:46:18
【问题描述】:

我想创建一个架构,其中实体 Chapter 的子代也是 Chapter。

它必须是一对多的关系,因为一章可以有很多孩子,但只有一个父母。

我发现很难在我的 Prisma 架构中定义它。我尝试了一些方法,但总是显示错误:

// 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?
}

有什么想法吗?

【问题讨论】:

    标签: postgresql next.js one-to-many database-schema prisma


    【解决方案1】:

    这是要走的路。父级可以有多个章节的一对多关系:

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

    我们在文档中也有这个:https://www.prisma.io/docs/concepts/components/prisma-schema/relations/self-relations#one-to-many-self-relations

    【讨论】:

      猜你喜欢
      • 2015-01-08
      • 2021-03-17
      • 2021-01-25
      • 2022-10-13
      • 2022-11-25
      • 2021-12-04
      • 2018-01-14
      • 2019-08-13
      • 2016-10-09
      相关资源
      最近更新 更多