Relationships between Tables

Learn about SQL table relationships and how they can be implemented with the Prisma ORM.

One core aspect of SQL is the relationships between tables—that is, how different tables relate to each other. There are four relationships in SQL:

  • One-to-one
  • One-to-many
  • Many-to-one
  • Many-to-many

One-to-one

A one-to-one relationship occurs when an entity is mapped to another entity uniquely, like when a record in a table maps to only one record in another table. A good example is a relationship between humans and their fingerprints.

In Prisma, we can achieve this with the @relation annotation. First, in the schema.prisma file, we define the model for fingerprints and humans as shown below. The model should include their unique IDs and other relevant information.

Press + to interact
// This is your Prisma schema file,
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Human {
id Int @default(autoincrement()) @id
email String
name String
}
model FingerPrint {
id Int @default(autoincrement()) @id
hash string @unique
}

Next, we use the @relation annotation to define the one-to-one relationship that exists between both models. We achieve this in SQL by mapping a column in one table to map the primary key of the other. Let’s call this column in the FingerPrint schema humandId. This will map to the primary ID of the Human schema.

We can then ...