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
id
field that will be the primary key - a
title
field - an optional
description
field createdAt
andupdatedAt
fields to keep track of when the category was created and last updated.- an association with the
Game
table
Add this model to the schema.prisma
file directly beneath the Game
model we created in the previous lesson:
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[]}
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 studio
If 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.
πππ