内省
使用 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
列名 | 类型 | 主键 | 外键 | 必填 | 默认值 |
---|---|---|---|---|---|
id | int | ✔️ | 否 | ✔️ | 自动增长 |
createdAt | datetime(3) | 否 | 否 | ✔️ | now() |
updatedAt | datetime(3) | 否 | 否 | ✔️ | |
title | varchar(255) | 否 | 否 | ✔️ | - |
content | varchar(191) | 否 | 否 | 否 | - |
published | tinyint(1) | 否 | 否 | ✔️ | false |
authorId | int | 否 | 否 | ✔️ | - |
Profile
列名 | 类型 | 主键 | 外键 | 必填 | 默认值 |
---|---|---|---|---|---|
id | int | ✔️ | 否 | ✔️ | 自动增长 |
bio | varchar(191) | 否 | 否 | 否 | - |
userId | int | 否 | 否 | ✔️ | - |
User
列名 | 类型 | 主键 | 外键 | 必填 | 默认值 |
---|---|---|---|---|---|
id | int | ✔️ | 否 | ✔️ | 自动增长 |
name | varchar(191) | 否 | 否 | 否 | - |
email | varchar(191) | 否 | 否 | ✔️ | - |
下一步,您将对数据库进行内省。内省的结果将是 Prisma Schema 中的一个数据模型。
运行以下命令对数据库进行内省
npx prisma db pull
此命令读取 .env
中定义的 DATABASE_URL
环境变量并连接到您的数据库。连接建立后,它将对数据库进行内省(即读取数据库 Schema)。然后它将 SQL 数据库 Schema 转换为 Prisma 数据模型。
内省完成后,您的 Prisma Schema 将被更新
数据模型现在看起来类似于这样
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 的数据模型是数据库 Schema 的声明式表示,并作为生成的 Prisma Client 库的基础。您的 Prisma Client 实例将暴露针对这些模型量身定制的查询。
然后,您需要使用关系字段添加数据之间所有缺失的关系
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 现在将保留手动添加的关系字段。
由于关系字段是虚拟的(即它们不直接在数据库中体现),您可以在 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 页面上了解更多信息。