Using Prisma Migrate
Creating the database schema
In this guide, you'll use Prisma Migrate to create the tables in your database.
To do so, first add the following Prisma data model to your Prisma schema in prisma/schema.prisma
:
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
model Profile {
id Int @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
profile Profile?
}
This data model defines three models (which will be mapped to tables in the underlying database):
Post
Profile
User
It also defines two relations:
- A one-to-many relation between
User
andPost
(i.e. "one user can have many posts") - A one-to-one relation between
User
andProfile
(i.e. "one user can have one profile")
To map your data model to the database schema, you need to use the prisma migrate
CLI commands:
npx prisma migrate dev --name init
This command did two things:
- It generated a new SQL migration file for this migration
- It ran the SQL migration file against the database
You can inspect the generated SQL migration file in the newly created prisma/migrations
directory.
Prisma Studio is a visual editor for your database. You can open it with the following command in your terminal:
npx prisma studio
Since you just created the database, you won't see any records but you can take a look at the empty User
, Post
and Profile
tables.
Great, you now created three tables in your database with Prisma Migrate. In the next section, you'll learn how to install Prisma Client which lets you send queries to your database from your TypeScript app.