跳到主要内容

内省

使用 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 内的数据模型

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

npx prisma db pull

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

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

Introspect your database

数据模型现在看起来类似于这样

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 的数据模型是您的数据库 schema 的声明式表示,并且是生成的 Prisma Client 库的基础。您的 Prisma Client 实例将公开针对这些模型定制的查询。

然后,您将需要使用关系字段在您的数据之间添加任何缺失的关系

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 现在将保留手动添加的关系字段。

因为关系字段是虚拟的(即,它们不会直接在数据库中体现),所以您可以手动在您的 Prisma schema 中重命名它们,而无需触及数据库。

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

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

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

假设您从基于 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页面上了解更多关于此内容的信息。