prisma / prisma

prisma / prisma

Prisma Quickstart • Website • Docs • Examples • Blog • Discord • Twitter • Youtube Prisma 快速入门 • 官网 • 文档 • 示例 • 博客 • Discord • Twitter • Youtube

What is Prisma?

什么是 Prisma?

Prisma ORM is a next-generation ORM that consists of these tools: Prisma ORM 是一款新一代 ORM,由以下工具组成:

  • Prisma Client: Auto-generated and type-safe query builder for Node.js & TypeScript
  • Prisma Client: 为 Node.js 和 TypeScript 自动生成且类型安全的查询构建器
  • Prisma Migrate: Declarative data modeling & migration system
  • Prisma Migrate: 声明式数据建模与迁移系统
  • Prisma Studio: GUI to view and edit data in your database
  • Prisma Studio: 用于查看和编辑数据库中数据的图形用户界面 (GUI)

Prisma Client can be used in any Node.js 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. If you need a database to use with Prisma ORM, check out Prisma Postgres or if you are looking for our MCP Server, head here. Prisma Client 可用于任何 Node.js 或 TypeScript 后端应用程序(包括无服务器应用和微服务)。无论是 REST API、GraphQL API、gRPC API 还是任何其他需要数据库的应用场景均可使用。如果您需要为 Prisma ORM 配套数据库,请查看 Prisma Postgres;如果您正在寻找我们的 MCP Server,请点击此处。


Getting started

入门指南

Quickstart (5min) 快速入门 (5分钟)

The fastest way to get started with Prisma is by following the quickstart guides. You can choose either of two databases: 开始使用 Prisma 最快的方法是参考快速入门指南。您可以选择以下两种数据库之一:

  • Prisma Postgres
  • SQLite

Bring your own database 使用自有数据库

If you already have your own database, you can follow these guides: 如果您已经拥有自己的数据库,可以参考以下指南:

  • Add Prisma to an existing project
  • 将 Prisma 添加到现有项目中
  • Set up a new project with Prisma from scratch
  • 从零开始设置一个使用 Prisma 的新项目

How Prisma ORM works

Prisma ORM 的工作原理

This section provides a high-level overview of how Prisma ORM works and its most important technical components. For a more thorough introduction, visit the Prisma documentation. 本节简要概述了 Prisma ORM 的工作原理及其最重要的技术组件。如需更深入的了解,请访问 Prisma 文档。

The Prisma schema Prisma Schema

Every project that uses a tool from the Prisma toolkit starts with a Prisma schema file. The Prisma schema allows developers to define their application models in an intuitive data modeling language and configure generators. 每个使用 Prisma 工具包的项目都始于一个 Prisma schema 文件。Prisma schema 允许开发者使用直观的数据建模语言定义应用程序模型,并配置生成器。

// Data source
datasource db {
  provider = "postgresql"
}

// Generator
generator client {
  provider = "prisma-client"
  output   = "../generated"
}

// Data model
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[]
}

In this schema, you configure three things: 在此 schema 中,您可以配置三项内容:

  • Data source: Specifies your database type and thus defines the features and data types you can use in the schema
  • 数据源 (Data source):指定数据库类型,从而定义您在 schema 中可使用的功能和数据类型
  • Generator: Indicates that you want to generate Prisma Client
  • 生成器 (Generator):指示您希望生成 Prisma Client
  • Data model: Defines your application models
  • 数据模型 (Data model):定义您的应用程序模型

prisma.config.ts

prisma.config.ts

Database connection details are defined via prisma.config.ts. 数据库连接详情通过 prisma.config.ts 定义。

import { defineConfig } from 'prisma/config'

export default defineConfig({
  datasource: {
    url: 'postgres://...',
  },
})

If you store the database connection string in process.env, an env function can help you access it in a type safe way and throw an error if it is missing at run time: 如果您将数据库连接字符串存储在 process.env 中,env 函数可以帮助您以类型安全的方式访问它,并在运行时缺失时抛出错误:

import { defineConfig, env } from 'prisma/config'

export default defineConfig({
  datasource: {
    url: env('DATABASE_URL'),
  },
})

Prisma ORM does not load the .env files for you automatically. If you want to populate the environment variables from a .env file, consider using a package such as dotenv or @dotenvx/dotenvx. The configuration file may look like this in that case: Prisma ORM 不会自动为您加载 .env 文件。如果您希望从 .env 文件中填充环境变量,请考虑使用 dotenv@dotenvx/dotenvx 等包。在这种情况下,配置文件可能如下所示:

import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'

export default defineConfig({
  datasource: {
    url: env('DATABASE_URL'),
  },
})

To start a local PostgreSQL development server without using Docker and without any configuration, run prisma dev: 若要在不使用 Docker 且无需任何配置的情况下启动本地 PostgreSQL 开发服务器,请运行 prisma dev

npx prisma dev

Alternatively, spin up an instant Prisma Postgres® database in the cloud: 或者,在云端快速启动一个 Prisma Postgres® 数据库:

npx create-db --interactive

The Prisma data model

Prisma 数据模型

On this page, the focus is on the data model. You can learn more about Data sources and Generators on the respective docs pages. 本页重点介绍数据模型。您可以访问相应的文档页面了解更多关于数据源和生成器的信息。

Functions of Prisma models Prisma 模型的功能

The data model is a collection of models. A model has two major functions: 数据模型是模型的集合。模型具有两大功能:

  1. Represent a table in the underlying database
  2. 代表底层数据库中的一张表
  3. Provide the foundation for the queries in the Prisma Client API
  4. 为 Prisma Client API 中的查询提供基础

Getting a data model 获取数据模型

There are two major workflows for “getting” a data model into your Prisma schema: 将数据模型“获取”到 Prisma schema 中主要有两种工作流:

  1. Generate the data model from introspecting a database
  2. 通过内省 (Introspect) 数据库生成数据模型
  3. Manually writing the data model and mapping it to the database with Prisma Migrate
  4. 手动编写数据模型,并使用 Prisma Migrate 将其映射到数据库

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 Client,它将为定义的模型公开 CRUD 及更多查询功能。如果您使用 TypeScript,将获得所有查询的完全类型安全(即使仅检索模型字段的子集时也是如此)。


Accessing your database with Prisma Client

使用 Prisma Client 访问数据库

Step 1: Install Prisma 第一步:安装 Prisma

First, install Prisma CLI as a development dependency and Prisma Client: 首先,将 Prisma CLI 安装为开发依赖项,并安装 Prisma Client:

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

Step 2: Set up your Prisma schema 第二步:设置 Prisma schema

Ensure your Prisma schema includes a generator block with an output path specified: 确保您的 Prisma schema 包含一个指定了输出路径的 generator 块:

generator client {
  provider = "prisma-client"
  output   = "../generated"
}

datasource db {
  provider = "postgresql" // mysql, sqlite, sqlserver, mongodb or cockroachdb
}

Step 3: Configure Prisma Config 第三步:配置 Prisma Config

Configure the Prisma CLI using a prisma.config.ts file. This file configures Prisma CLI subcommands like migrate and studio. Create a prisma.config.ts file in your project root: 使用 prisma.config.ts 文件配置 Prisma CLI。该文件用于配置 migratestudio 等 Prisma CLI 子命令。在项目根目录下创建 prisma.config.ts 文件:

import { defineConfig, env } from 'prisma/config'

type Env = { DATABASE_URL: string }

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: {
    path: 'prisma/migrations',
  },
  datasource: {
    url: env<Env>('DATABASE_URL'),
  },
})

Note: Environment variables from .env files are not automatically loaded when using prisma.config.ts. You can use dotenv by importing dotenv/config at the top of your config file. For Bun, .env files are automatically loaded. Learn more about Prisma Config and all available configuration options. 注意:使用 prisma.config.ts 时,来自 .env 文件的环境变量不会自动加载。您可以在配置文件顶部导入 dotenv/config 来使用 dotenv。对于 Bun,.env 文件会自动加载。了解更多关于 Prisma Config 及所有可用配置选项的信息。

Step 4: Generate Prisma Client 第四步:生成 Prisma Client

Generate Prisma Client with the following command: 使用以下命令生成 Prisma Client:

npx prisma generate

This command reads your Prisma schema and generates the Prisma Client code in the location specified by the output path in your generator configuration. After you change your data model, you’ll need to manually re-generate Prisma Client to ensure the generated code gets updated: 此命令会读取您的 Prisma schema,并在生成器配置中指定的输出路径位置生成 Prisma Client 代码。更改数据模型后,您需要手动重新生成 Prisma Client,以确保生成的代码得到更新:

npx prisma generate

Refer to the documentation for more information about “generating the Prisma client”. 有关“生成 Prisma Client”的更多信息,请参阅文档。

Step 5: Use Prisma Client to send queries to your database 第五步:使用 Prisma Client 向数据库发送查询

Once the Prisma Client is… 一旦 Prisma Client…