One-to-many relationships in Prisma
What is a database relationship?
Section titled “What is a database relationship?”A database relationship is a connection between two tables.
In a relational database, such as SQLite, tables can be connected to each other using foreign keys. These foreign keys are used to establish a link between the data in the two tables.
We are going to set up a database relationship using Prisma. We will create a new table called Category and link it to the Game table.
Each game must belong to a category, and each category can have many games. From the three types of relationships described above, which one do you think this is? 🤔
Setting up a database relationship
Section titled “Setting up a database relationship”Create the Category table
Section titled “Create the Category table”We will start by creating a new table called Category in the schema.prisma file. This table will have the following attributes:
- an
idfield that will be the primary key - a
titlefield - an optional
descriptionfield createdAtandupdatedAtfields to keep track of when the category was created and last updated.- an association with the
Gametable
Add this model to the schema.prisma file directly beneath the Game model:
model Game { id String @id @default(cuid()) title String description String price Float rating Float releaseDate DateTime
createdAt DateTime @default(now()) updatedAt DateTime @updatedAt categoryId String? category Category? @relation(fields: [categoryId], references: [id])}
model Category { id String @id @default(cuid()) title String description String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt games Game[]}
model User {5 collapsed lines
id String @id @default(cuid()) email String @unique
createdAt DateTime @default(now()) updatedAt DateTime @updatedAt}Apply the changes to the database
Section titled “Apply the changes to the database”We have made changes to the schema.prisma file, but these changes have not yet been applied to the database.
If you remember from our previous lesson, we can apply these changes to the database by generating a migration file. This migration will contain the SQL commands needed to update the database schema to match the new schema.prisma file.
Checking the database
Section titled “Checking the database”Finally, let’s fire up Prisma Studio to check that the changes have been applied to the database.
npx prisma studioIf all is good, you should see the new (empty!) Category table in your browser:

Next, we will learn how to use seed files to populate our database with information.
🚀🚀🚀