You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Prisma中实现用户ID与日历类型的复合唯一性约束?

实现同一用户同类型日历的唯一性约束

要实现你需要的约束,核心是在中间关联表CalendarsOnUsers中添加calendarType字段,并创建userId与calendarType的复合唯一约束。具体修改如下:

model User {
  id                Int      @id @default(autoincrement())
  calendars         CalendarsOnUsers[]
}

model Calendar {
  id            Int     @id @default(autoincrement())
  calendarType  String
  users         CalendarsOnUsers[]
  calendarEvents  CalendarEventsOnCalendars[]
}

model CalendarsOnUsers {
  user          User     @relation(fields: [userId], references: [id])
  userId        Int
  calendar      Calendar @relation(fields: [calendarId], references: [id])
  calendarId    Int
  // 添加与关联日历一致的类型字段
  calendarType  String

  // 原有的联合主键
  @@id([userId, calendarId])
  // 添加复合唯一约束,确保同一用户不能拥有同类型的多个日历
  @@unique([userId, calendarType])
}

关键说明:

  • 由于唯一性约束需要同时关联userId和calendarType,而calendarType属于Calendar模型,必须将其冗余到中间表中才能创建跨字段的唯一约束(Prisma的表级约束只能作用于当前模型的字段)。
  • 添加@@unique([userId, calendarType])后,数据库会自动阻止同一用户关联多个同类型日历的操作。
  • 为了保证数据一致性,建议在业务逻辑中确保CalendarsOnUsers的calendarType始终与关联Calendar的calendarType保持一致,或者在数据库层面添加触发器实现强一致性。

内容的提问来源于stack exchange,提问作者John Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:50:29