Skip to main content

将 Prisma Migrate 与 TypeScript 和 Prisma Postgres 结合使用

创建数据库架构

¥Creating the database schema

在本指南中,你将使用 Prisma 迁移 在数据库中创建表。

¥In this guide, you'll use Prisma Migrate to create the tables in your database.

为此,首先将以下 Prisma 数据模型添加到 prisma/schema.prisma 中的 Prisma 模式中:

¥To do so, first add the following Prisma data model to your Prisma schema in prisma/schema.prisma:

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?
}

此数据模型定义了三个 models(将映射到底层数据库中的表):

¥This data model defines three models (which will be mapped to tables in the underlying database):

  • Post

  • Profile

  • User

它还定义了两个 relations

¥It also defines two relations:

  • UserPost 之间的一对多关系(即 "一个用户可以发布多条帖子")

    ¥A one-to-many relation between User and Post (i.e. "one user can have many posts")

  • UserProfile 之间的一对一关系(即 "一个用户可以拥有一个配置文件")

    ¥A one-to-one relation between User and Profile (i.e. "one user can have one 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 did two things:

  1. 它为此迁移生成了一个新的 SQL 迁移文件

    ¥It generated a new SQL migration file for this migration

  2. 它针对数据库运行了 SQL 迁移文件

    ¥It ran the SQL migration file against the database

你可以在新创建的 prisma/migrations 目录中检查生成的 SQL 迁移文件。

¥You can inspect the generated SQL migration file in the newly created prisma/migrations directory.

在 Prisma Studio 中探索你的数据库

Prisma 工作室 是数据库的可视化编辑器。你可以在终端中使用以下命令打开它:

¥Prisma Studio is a visual editor for your database. You can open it with the following command in your terminal:

npx prisma studio

由于你刚刚创建了数据库,因此你看不到任何记录,但你可以查看空的 UserPostProfile 表。

¥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.

太好了,你现在使用 Prisma Migrate 在数据库中创建了三个表。在下一节中,你将了解如何安装 Prisma Client,它允许你从 TypeScript 应用向数据库发送查询。

¥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.