跳到主要内容

内省

使用 Prisma ORM 内省你的数据库

在本指南中,我们将使用一个包含三个表的演示 SQL schema

CREATE TABLE `Post` (
`id` int NOT NULL AUTO_INCREMENT,
`createdAt` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updatedAt` datetime(3) NOT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`content` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`published` tinyint(1) NOT NULL DEFAULT '0',
`authorId` int NOT NULL,
PRIMARY KEY (`id`),
KEY `Post_authorId_idx` (`authorId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `Profile` (
`id` int NOT NULL AUTO_INCREMENT,
`bio` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`userId` int NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `Profile_userId_key` (`userId`),
KEY `Profile_userId_idx` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `User` (
`id` int NOT NULL AUTO_INCREMENT,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `User_email_key` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
展开以查看表的图形概览

Post

列名类型主键外键必需默认值
idint✔️✔️自增
createdAtdatetime(3)✔️now()
updatedAtdatetime(3)✔️
titlevarchar(255)✔️-
contentvarchar(191)-
publishedtinyint(1)✔️false
authorIdint✔️-

Profile

列名类型主键外键必需默认值
idint✔️✔️自增
biovarchar(191)-
userIdint✔️-

User

列名类型主键外键必需默认值
idint✔️✔️自增
namevarchar(191)-
emailvarchar(191)✔️-

下一步,你将内省你的数据库。内省的结果将是你的 Prisma schema 中的一个 data model。

运行以下命令来内省你的数据库

npx prisma db pull

此命令读取在 .env 中定义的 DATABASE_URL 环境变量,并连接到你的数据库。连接建立后,它会内省数据库(即读取数据库 schema)。然后,它将数据库 schema 从 SQL 转换为 Prisma data model。

内省完成后,你的 Prisma schema 将会被更新

Introspect your database

现在 data model 看起来类似于这样

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime
title String @db.VarChar(255)
content String?
published Boolean @default(false)
authorId Int

@@index([authorId])
}

model Profile {
id Int @id @default(autoincrement())
bio String?
userId Int @unique

@@index([userId])
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
信息

有关 schema 定义的详细信息,请参阅 Prisma schema 参考。

Prisma 的 data model 是你的数据库 schema 的声明式表示,并且是生成的 Prisma Client 库的基础。你的 Prisma Client 实例将公开针对这些模型定制的查询。

然后,你需要使用 relation fields 在你的数据之间添加任何缺失的关系

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime
title String @db.VarChar(255)
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int

@@index([authorId])
}

model Profile {
id Int @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique

@@index([userId])
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
profile Profile?
}

之后,再次对你的数据库运行内省

npx prisma db pull

Prisma Migrate 现在将保留手动添加的 relation fields。

由于 relation fields 是虚拟的(即它们不会直接在数据库中体现),你可以在你的 Prisma schema 中手动重命名它们,而无需触及数据库。

在此示例中,数据库 schema 遵循 Prisma ORM 模型的命名约定。这优化了生成的 Prisma Client API 的人体工程学。

使用自定义模型和字段名称

但有时,你可能想要对在 Prisma Client API 中公开的列和表的名称进行额外的更改。一个常见的例子是将数据库 schema 中常用的 snake_case 表示法转换为 PascalCase 和 camelCase 表示法,这对于 JavaScript/TypeScript 开发人员来说感觉更自然。

假设你从基于 snake_case 表示法的内省中获得了以下模型

model my_user {
user_id Int @id @default(autoincrement())
first_name String?
last_name String @unique
}

如果你为此模型生成了 Prisma Client API,它将在其 API 中采用 snake_case 表示法

const user = await prisma.my_user.create({
data: {
first_name: 'Alice',
last_name: 'Smith',
},
})

如果你不想在你的 Prisma Client API 中使用来自数据库的表和列名,你可以使用 @map 和 @@map 来配置它们

model MyUser {
userId Int @id @default(autoincrement()) @map("user_id")
firstName String? @map("first_name")
lastName String @unique @map("last_name")

@@map("my_user")
}

通过这种方法,你可以随意命名你的模型及其字段,并使用 @map(用于字段名称)和 @@map(用于模型名称)来指向底层表和列。你的 Prisma Client API 现在看起来如下

const user = await prisma.myUser.create({
data: {
firstName: 'Alice',
lastName: 'Smith',
},
})

在配置你的 Prisma Client API 页面上了解更多相关信息。