Sikau

Prisma · Day 9 · about 30 min

Many-to-many

Join models with extra fields, and implicit relations.

Students and courses

A student takes many courses; a course has many students. In SQL that needs a join table. In Prisma you model it explicitly — a model with two relations and a compound id — whenever the link carries data like a grade.

Explicit and implicit

model Student {
  id          Int          @id @default(autoincrement())
  name        String
  enrollments Enrollment[]
}

model Course {
  id          Int          @id @default(autoincrement())
  code        String       @unique
  enrollments Enrollment[]
}

model Enrollment {
  student   Student @relation(fields: [studentId], references: [id])
  studentId Int
  course    Course  @relation(fields: [courseId], references: [id])
  courseId  Int
  grade     Int?

  @@id([studentId, courseId])
}

// Implicit: no join model, Prisma manages a hidden _PostToTag table
model Post { id Int @id  tags Tag[] }
model Tag  { id Int @id  posts Post[] }

With an explicit model you query through it: include: { enrollments: { include: { course: true } } }.

The rest of this lesson

  • Implicit many-to-manyexplain
  • Querying through a join modelexplain
  • Enrol twice?predict
  • Implicit or explicit?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Prisma