Prisma: What's the best way to model a many-to-many relationship with extra fields? #201962
-
🏷️ Discussion TypeQuestion BodyHi everyone, I'm learning Prisma and working on a project where users can enroll in courses. A user can enroll in multiple courses, and a course can have multiple users. I also need to store additional information for each enrollment, such as:
Should I use Prisma's implicit many-to-many relation, or should I create an explicit join model? If an explicit model is recommended, could someone explain why it's the better approach and share a simple schema example? Thanks! Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
When you need to store additional information about the relationship itself (such as enrolledAt, progress, or status), an explicit many-to-many relation is the recommended approach. Instead of using Prisma's implicit many-to-many relation, create a dedicated join model. Example: model User { model Course { model Enrollment { enrolledAt DateTime @default(now()) user User @relation(fields: [userId], references: [id]) @@id([userId, courseId]) Using an explicit join model gives you several advantages:
Implicit many-to-many relations are a good choice when you only need to know that two models are connected. However, once you need to store extra information about that connection, an explicit join model is the recommended and more scalable approach. |
Beta Was this translation helpful? Give feedback.
When you need to store additional information about the relationship itself (such as enrolledAt, progress, or status), an explicit many-to-many relation is the recommended approach.
Instead of using Prisma's implicit many-to-many relation, create a dedicated join model.
Example:
model User {
id String @id @default(cuid())
enrollments Enrollment[]
}
model Course {
id String @id @default(cuid())
enrollments Enrollment[]
}
model Enrollment {
userId String
courseId String
enrolledAt DateTime @default(now())
progress Int @default(0)
status String
user User @relation(fields: [userId], references: [id])
course Course @relation(fields: [courseId], references: [id])
@@id([userId, courseId])
}
Usin…