简短的回答:Prefer the implicit relationship unless you need to store additional meta-information about the relation itself.
例如,在隐式版本中,Post
和Category
之间的普通n-m关系如下所示:
model Post {
id Int @id @default(autoincrement())
title String
categories Category[]
}
model Category {
id Int @id @default(autoincrement())
name String
posts Post[]
}
现在,如果您需要存储有关此关系的元数据,例如已将信息when和Post
添加到Category
,则应创建一个显式版本:
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])
}
主要的权衡实际上是convenience.使用隐式关系要简单得多,因为关系表是在幕后为您维护的.此外,Prisma客户端API中的关系查询更易于使用,因为您在connect
API中保存了"一跳"(使用显式的关系表,您始终必须在Prisma客户端查询中"遍历"关系表).
此外,您还可以在以后将隐式关系迁移到显式关系.因此,您总是可以从隐式关系开始,并在以后需要时将其转换为显式关系.