Skip to main content

什么是 Prisma ORM?

Prisma ORM 是 open-source 下一代 ORM。它由以下部分组成:

¥Prisma ORM is an open-source next-generation ORM. It consists of the following parts:

  • Prisma 客户端:适用于 Node.js 和 TypeScript 的自动生成且类型安全的查询构建器

    ¥Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript

  • Prisma 迁移:迁移系统

    ¥Prisma Migrate: Migration system

  • Prisma 工作室:用于查看和编辑数据库中的数据的 GUI。

    ¥Prisma Studio: GUI to view and edit data in your database.

    信息

    Prisma Studio 是 Prisma ORM 唯一非开源的部分。你只能在本地运行 Prisma Studio。

    ¥Prisma Studio is the only part of Prisma ORM that is not open source. You can only run Prisma Studio locally.

Prisma Client 可在任何 Node.js(支持的版本)或 TypeScript 后端应用(包括无服务器应用和微服务)中使用。这可以是 剩余 APIGraphQL API、gRPC API 或任何其他需要数据库的东西。

¥Prisma Client can be used in any Node.js (supported versions) or TypeScript backend application (including serverless applications and microservices). This can be a REST API, a GraphQL API, a gRPC API, or anything else that needs a database.

Prisma ORM 如何工作?

¥How does Prisma ORM work?

Prisma 架构

¥The Prisma schema

每个使用 Prisma ORM 工具包中的工具的项目都以 Prisma 架构 开头。Prisma 架构允许开发者以直观的数据建模语言定义其应用模型。它还包含与数据库的连接并定义了一个生成器:

¥Every project that uses a tool from the Prisma ORM toolkit starts with a Prisma schema. The Prisma schema allows developers to define their application models in an intuitive data modeling language. It also contains the connection to a database and defines a generator:

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}

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

注意:Prisma 模式具有强大的数据建模功能。例如,它允许你定义 "Prisma 级" 关系字段,这将使使用 Prisma 客户端 API 中的关系 变得更容易。在上面的例子中,User 上的 posts 字段仅在 "Prisma 级" 上定义,这意味着它不会在底层数据库中表现为外键。

¥Note: The Prisma schema has powerful data modeling features. For example, it allows you to define "Prisma-level" relation fields which will make it easier to work with relations in the Prisma Client API. In the case above, the posts field on User is defined only on "Prisma-level", meaning it does not manifest as a foreign key in the underlying database.

在此架构中,你配置三件事:

¥In this schema, you configure three things:

  • 数据源:指定你的数据库连接(通过环境变量)

    ¥Data source: Specifies your database connection (via an environment variable)

  • 生成器:表示你要生成 Prisma Client

    ¥Generator: Indicates that you want to generate Prisma Client

  • 数据模型:定义你的应用模型

    ¥Data model: Defines your application models

Prisma 架构数据模型

¥The Prisma schema data model

在此页面上,重点是数据模型。你可以在相应的文档页面上了解有关 数据源生成器 的更多信息。

¥On this page, the focus is on the data model. You can learn more about Data sources and Generators on the respective docs pages.

Prisma 模式数据模型的功能

¥Functions of Prisma schema data models

数据模型是 models 的集合。模型有两个主要功能:

¥The data model is a collection of models. A model has two major functions:

  • 表示关系数据库中的表或 MongoDB 中的集合

    ¥Represent a table in relational databases or a collection in MongoDB

  • 为 Prisma 客户端 API 中的查询提供基础

    ¥Provide the foundation for the queries in the Prisma Client API

获取数据模型

¥Getting a data model

将 "getting" 数据模型添加到 Prisma 模式中有两个主要工作流程:

¥There are two major workflows for "getting" a data model into your Prisma schema:

定义数据模型后,你可以 生成 Prisma 客户端,这将公开 CRUD 和对已定义模型的更多查询。如果你使用 TypeScript,你将获得所有查询的完整类型安全性(即使仅检索模型字段的子集)。

¥Once the data model is defined, you can generate Prisma Client which will expose CRUD and more queries for the defined models. If you're using TypeScript, you'll get full type-safety for all queries (even when only retrieving the subsets of a model's fields).

使用 Prisma 客户端访问你的数据库

¥Accessing your database with Prisma Client

生成 Prisma 客户端

¥Generating Prisma Client

使用 Prisma 客户端的第一步是安装 @prisma/clientprisma npm 包:

¥The first step when using Prisma Client is installing the @prisma/client and prisma npm packages:

npm install prisma --save-dev
npm install @prisma/client

然后,你可以运行 prisma generate

¥Then, you can run prisma generate:

npx prisma generate

prisma generate 命令读取 Prisma 模式并生成 Prisma 客户端代码。代码是 默认生成到 node_modules/.prisma/client 文件夹

¥The prisma generate command reads your Prisma schema and generates Prisma Client code. The code is generated into the node_modules/.prisma/client folder by default.

更改数据模型后,你需要通过运行 prisma generate 手动重新生成 Prisma 客户端,以确保 node_modules/.prisma/client 中的代码得到更新。

¥After you change your data model, you'll need to manually re-generate Prisma Client by running prisma generate to ensure the code inside node_modules/.prisma/client gets updated.

使用 Prisma 客户端向数据库发送查询

¥Using Prisma Client to send queries to your database

生成 Prisma 客户端后,你可以将其导入代码中并向数据库发送查询。这就是设置代码的样子。

¥Once Prisma Client has been generated, you can import it in your code and send queries to your database. This is what the setup code looks like.

导入并实例化 Prisma 客户端

¥Import and instantiate Prisma Client

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

现在你可以开始通过生成的 Prisma 客户端 API 发送查询,以下是一些示例查询。请注意,所有 Prisma 客户端查询都会返回普通的旧 JavaScript 对象。

¥Now you can start sending queries via the generated Prisma Client API, here are a few sample queries. Note that all Prisma Client queries return plain old JavaScript objects.

了解有关 Prisma 客户端 API 参考 中可用操作的更多信息。

¥Learn more about the available operations in the Prisma Client API reference.

从数据库中检索所有 User 条记录

¥Retrieve all User records from the database

// Run inside `async` function
const allUsers = await prisma.user.findMany()
在每个返回的 User 对象上包含 posts 关系

¥Include the posts relation on each returned User object

// Run inside `async` function
const allUsers = await prisma.user.findMany({
include: { posts: true },
})
过滤所有包含 "prisma"Post 记录

¥Filter all Post records that contain "prisma"

// Run inside `async` function
const filteredPosts = await prisma.post.findMany({
where: {
OR: [
{ title: { contains: 'prisma' } },
{ content: { contains: 'prisma' } },
],
},
})
在同一查询中创建新的 User 和新的 Post 记录

¥Create a new User and a new Post record in the same query

// Run inside `async` function
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Join us for Prisma Day 2020' },
},
},
})
更新现有的 Post 记录

¥Update an existing Post record

// Run inside `async` function
const post = await prisma.post.update({
where: { id: 42 },
data: { published: true },
})

与 TypeScript 一起使用

¥Usage with TypeScript

请注意,使用 TypeScript 时,此查询的结果将是静态类型的,这样你就不会意外访问不存在的属性(并且在编译时捕获任何拼写错误)。在文档的 生成类型的高级用法 页面上了解有关利用 Prisma Client 生成的类型的更多信息。

¥Note that when using TypeScript, the result of this query will be statically typed so that you can't accidentally access a property that doesn't exist (and any typos are caught at compile-time). Learn more about leveraging Prisma Client's generated types on the Advanced usage of generated types page in the docs.

典型的 Prisma ORM 工作流程

¥Typical Prisma ORM workflows

如上所述,有两种方法可以将你的数据模型放入 Prisma 架构中。根据你选择的方法,你的主要 Prisma ORM 工作流程可能会有所不同。

¥As mentioned above, there are two ways for "getting" your data model into the Prisma schema. Depending on which approach you choose, your main Prisma ORM workflow might look different.

Prisma 迁移

¥Prisma Migrate

使用 Prisma Migrate(Prisma ORM 的集成数据库迁移工具),工作流程如下所示:

¥With Prisma Migrate, Prisma ORM's integrated database migration tool, the workflow looks as follows:

  1. 手动调整你的 Prisma 架构数据模型

    ¥Manually adjust your Prisma schema data model

  2. 使用 prisma migrate dev CLI 命令迁移开发数据库

    ¥Migrate your development database using the prisma migrate dev CLI command

  3. 在你的应用代码中使用 Prisma Client 来访问你的数据库

    ¥Use Prisma Client in your application code to access your database

Typical workflow with Prisma Migrate

要了解有关 Prisma Migrate 工作流程的更多信息,请参阅:

¥To learn more about the Prisma Migrate workflow, see:

SQL 迁移和内省

¥SQL migrations and introspection

如果由于某种原因,你不能或不想使用 Prisma Migrate,你仍然可以使用内省从数据库架构更新 Prisma 架构。使用 SQL 迁移和内省时的典型工作流程略有不同:

¥If for some reason, you can not or do not want to use Prisma Migrate, you can still use introspection to update your Prisma schema from your database schema. The typical workflow when using SQL migrations and introspection is slightly different:

  1. 使用 SQL 或第三方迁移工具手动调整数据库架构

    ¥Manually adjust your database schema using SQL or a third-party migration tool

  2. (重新)检查你的数据库

    ¥(Re-)introspect your database

  3. 可选 (重新)配置你的 Prisma 客户端 API

    ¥Optionally (re-)configure your Prisma Client API

  4. (重新)生成 Prisma 客户端

    ¥(Re-)generate Prisma Client

  5. 在你的应用代码中使用 Prisma Client 来访问你的数据库

    ¥Use Prisma Client in your application code to access your database

Introspect workflow

要了解有关内省工作流程的更多信息,请参阅 内省部分

¥To learn more about the introspection workflow, please refer the introspection section.