Create a Model for a Table and Run Migrations

Ryan Chenkie
InstructorRyan Chenkie

Share this video with your friends

Send Tweet
Published 4 months ago
Updated 2 months ago

Prisma offers a powerful database modeling language called the Prisma Schema Language. It allows us to describe the shape of our tables, the columns they should have (and their types), and relations between tables. In this lesson, we get started with our first table in our Prisma Schema file.

Instructor: [0:00] Schema.prisma, this file here uses the Prisma Schema Language, the PSL. One of the key words in the Prisma Schema Language is model. Model is used to describe a table in our database. For this database, the first table that we'll want to have is going to be a products table. We can create a model called product.

[0:20] Every table needs to have a unique identifier. Most commonly, this is going to be an ID for the table. There are several ways that we can construct IDs. We can use an auto-incrementing integer, for example, or we can use a string, and use something like a collision-resistant unique ID.

[0:36] Let's opt to use the cuid() for this table. What we'll do is mark it as the primary key using the add ID symbol here. Then we'll have @default will be cuid() for collision-resistant unique ID. Some other fields that we'll want on this table will include name. That should be a string. We'll also want a description for the product. That's a string as well.

[1:00] For now, let's have one more field, and that will be the price for the product. Price, we will express as an integer. We'll keep this as the number of cents that the product costs. Instead of opting for a float, where we can do fractions, instead, we'll keep everything in cents in the database. Then we will display in dollars on the page.

[1:18] Save the schema.prisma file. Come over to the command line and run npx prisma migrate dev. We need a name for the initial migration, and we can call it init. Once the migration runs, we will have a dev.db SQLite database in the prisma directory as well as a migrations directory.

[1:40] Within the migrations directory, we have a single directory for that initial migration, and it has the SQL that was generated to run the migration. This migration creates a product table and creates several columns in that table.