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

他们有没有什么权衡或者应该注意的事情?

推荐答案

简短的回答:Prefer the implicit relationship unless you need to store additional meta-information about the relation itself.

例如,在隐式版本中,PostCategory之间的普通n-m关系如下所示:

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

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

现在,如果您需要存储有关此关系的元数据,例如已将信息whenPost添加到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中的关系查询更易于使用,因为您在connectAPI中保存了"一跳"(使用显式的关系表,您始终必须在Prisma客户端查询中"遍历"关系表).

此外,您还可以在以后将隐式关系迁移到显式关系.因此,您总是可以从隐式关系开始,并在以后需要时将其转换为显式关系.

Database相关问答推荐

[mongodb],如何通过聚合获得具有许多不同字段的文档的最大值?子字段名称相同

如何以编程方式将产品添加到 Opencart 数据库

安装 SQL Server Management Studio Express后提示:Cannot open user default database. Login failed.

将光标中找到的值输出到logcat?

关闭连接会自动关闭语句和结果集吗?

授予对具有特定前缀的多个表的权限

在 postgresql 中将列从字符串更改为字符串数组

当您达到 SQL Server Express 4GB / 10GB 限制时会发生什么?

无法启动 MongoDB:Windows 中的系统错误 1067

PostgreSQL 字符变长限制

为 Java servlet 管理数据库连接的最佳方法

没有自动增量的sqlalchemy主键

dbvisualizer:在 Select 查询中设置最大行数

Sqlite 和 Python - 使用 fetchone() 返回字典?

MySQL中的eq_ref和ref类型是什么意思解释

Android - ViewHolder 模式是否在 CursorAdapter 中自动实现?

防止 PostgreSQL 有时 Select 错误的查询计划

分离实体和被管理实体

什么是提交日志(log)?

PostgreSQL 的 EXPLAIN ANALYZE 的 MySQL 类似功能是什么