Sikau

Prisma · Day 6 · about 30 min

Relations in the schema

One-to-many and one-to-one with @relation.

Foreign keys, described once

In SQL a relation is a foreign key column. In Prisma it is a relation field: a field whose type is another model. Prisma then lets you load and write related rows through it — no hand-written joins.

Two sides of a relation

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Customer {
  id      Int      @id @default(autoincrement())
  name    String
  orders  Order[]
  profile Profile?
}

model Order {
  id         Int      @id @default(autoincrement())
  total      Int
  customer   Customer @relation(fields: [customerId], references: [id])
  customerId Int
}

model Profile {
  id         Int      @id @default(autoincrement())
  phone      String
  customer   Customer @relation(fields: [customerId], references: [id], onDelete: Cascade)
  customerId Int      @unique
}

The rest of this lesson

  • Scalar and relation fieldsexplain
  • Self-relationsexplain
  • Which column exists?predict
  • Which field is which?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