将 Prisma Migrate 与 JavaScript 和 PostgreSQL 结合使用
创建数据库架构
¥Creating the database schema
在本指南中,你将使用 Prisma 迁移 在数据库中创建表。将以下数据模型添加到 prisma/schema.prisma
中的 Prisma 架构:
¥In this guide, you'll use Prisma Migrate to create the tables in your database. Add the following 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 @db.VarChar(255)
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?
}
要将数据模型映射到数据库模式,你需要使用 prisma migrate
CLI 命令:
¥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 does two things:
-
它为此迁移创建一个新的 SQL 迁移文件
¥It creates a new SQL migration file for this migration
-
它针对数据库运行 SQL 迁移文件
¥It runs the SQL migration file against the database
运行 prisma migrate dev
后,默认情况下会在后台调用 generate
。如果你的架构中定义了 prisma-client-js
生成器,这将检查是否安装了 @prisma/client
,如果缺少则安装它。
¥generate
is called under the hood by default, after running prisma migrate dev
. If the prisma-client-js
generator is defined in your schema, this will check if @prisma/client
is installed and install it if it's missing.
太棒了,你现在使用 Prisma Migrate 在数据库中创建了三个表 🚀
¥Great, you now created three tables in your database with Prisma Migrate 🚀