prisma 中隐式或显式的多对多关系

Dar*_*n V 9 database many-to-many plumatic-schema prisma

什么时候应该在 prisma 中使用隐式多对多关系,什么时候应该使用显式多对多关系?

他们有什么权衡或者需要注意的地方吗

nbu*_*urk 18

简短的回答:更喜欢隐式关系,除非您需要存储有关关系本身的附加元信息。

例如,Post和之间的简单 nm 关系Category在隐式版本中看起来像这样:

model Post {
  id         Int        @id @default(autoincrement())
  title      String
  categories Category[]
}

model Category {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您需要存储有关此关系的元数据,例如an已添加到 a时的信息,您应该创建一个显式版本:PostCategory

model Post {
  id         Int                 @id @default(autoincrement())
  title      String
  categories CategoriesOnPosts[]
}

model Category {
  id    Int                 @id @default(autoincrement())
  name  String
  posts CategoriesOnPosts[]
}

model CategoriesOnPosts {
  post       Post     @relation(fields: [postId], references: [id])
  postId     Int
  category   Category @relation(fields: [categoryId], references: [id])
  categoryId Int 

  assignedAt DateTime @default(now())

  @@id([postId, categoryId])
}
Run Code Online (Sandbox Code Playgroud)

主要的权衡确实是便利性。使用隐式关系要简单得多,因为关系表是在后台为您维护的。此外,Prisma 客户端 API 中的关系查询更易于使用,因为您可以在 API 中保存“一跳” connect(使用显式关系表,您始终必须在 Prisma 客户端查询中“遍历”关系表)。

此外,您还可以稍后将隐式关系迁移到显式关系。因此,您始终可以从隐式关系开始,然后在需要时将其转变为显式关系。