Skip to content

One-to-many relationships in Prisma

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? πŸ€”

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 and updatedAt 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:

prisma/schema.prisma
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[]
}

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.

Finally, let’s fire up Prisma Studio to check that the changes have been applied to the database.

Terminal window
npx prisma studio

If all is good, you should see the new (empty!) Category table in your browser:

Prisma Studio with Category table

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

πŸš€πŸš€πŸš€