Skip to main content

Prisma 架构参考

datasource

在 Prisma 模式中定义 数据源

¥Defines a data source in the Prisma schema.

字段

¥Fields

datasource 块接受以下字段:

¥A datasource block accepts the following fields:

名称必需的类型描述
provider是的字符串(postgresqlmysqlsqlitesqlservermongodbcockroachdb描述要使用的数据源连接器。
url是的字符串(网址)连接 URL 包括身份验证信息。大多数连接器使用 数据库提供的语法
shadowDatabaseUrl字符串(网址)Prisma Migrate 使用的影子数据库的连接 URL。允许你使用云托管数据库作为影子数据库。
directUrl字符串(网址)用于直接连接到数据库的连接 URL。

如果你在 url 参数中使用连接池 URL(例如,如果你使用 Prisma 加速 或 pgBouncer),则需要直接连接到数据库的 Prisma CLI 命令将使用 directUrl 参数中的 URL 。

Prisma Studio 5.1.0 及以上版本支持 directUrl 属性。

使用 Prisma Postgres 数据库时不需要 directUrl 属性。
relationMode字符串(foreignKeysprisma设置 参照完整性 是由数据库中的外键强制执行还是在 Prisma 客户端中模拟。

在 3.1.1 及更高版本中预览。该字段在 4.5.0 及更高版本中命名为 relationMode,之前命名为 referentialIntegrity
extensions字符串列表(PostgreSQL 扩展名称)让你 在你的架构中表示 PostgreSQL 扩展。仅在 Prisma ORM 版本 4.5.0 及更高版本中提供 PostgreSQL 预览版。

可以使用以下提供商:

¥The following providers are available:

备注

¥Remarks

  • 一个模式中只能有一个 datasource 块。

    ¥You can only have one datasource block in a schema.

  • datasource db 是约定 - 但是,你可以为数据源指定任何名称 - 例如,datasource mysqldatasource data

    ¥datasource db is convention - however, you can give your data source any name - for example, datasource mysql or datasource data.

示例

¥Examples

指定 PostgreSQL 数据源

¥Specify a PostgreSQL data source

在此示例中,目标数据库可使用以下凭据:

¥In this example, the target database is available with the following credentials:

  • 用户:johndoe

    ¥User: johndoe

  • 密码:mypassword

    ¥Password: mypassword

  • 主持人:localhost

    ¥Host: localhost

  • 港口:5432

    ¥Port: 5432

  • 数据库名称:mydb

    ¥Database name: mydb

  • 架构名称:public

    ¥Schema name: public

datasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public"
}

了解有关 PostgreSQL 连接字符串 此处 的更多信息。

¥Learn more about PostgreSQL connection strings here.

通过环境变量指定 PostgreSQL 数据源

¥Specify a PostgreSQL data source via an environment variable

在此示例中,目标数据库可使用以下凭据:

¥In this example, the target database is available with the following credentials:

  • 用户:johndoe

    ¥User: johndoe

  • 密码:mypassword

    ¥Password: mypassword

  • 主持人:localhost

    ¥Host: localhost

  • 港口:5432

    ¥Port: 5432

  • 数据库名称:mydb

    ¥Database name: mydb

  • 架构名称:public

    ¥Schema name: public

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

当运行需要数据库连接 URL(例如 prisma generate)的 Prisma CLI 命令时,你需要确保设置了 DATABASE_URL 环境变量。

¥When running a Prisma CLI command that needs the database connection URL (e.g. prisma generate), you need to make sure that the DATABASE_URL environment variable is set.

一种方法是创建包含以下内容的 .env 文件。请注意,该文件必须与 schema.prisma 文件位于同一目录中才能自动获取 Prisma CLI。

¥One way to do so is by creating a .env file with the following contents. Note that the file must be in the same directory as your schema.prisma file to automatically picked up the Prisma CLI.

DATABASE_URL=postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public

指定 MySQL 数据源

¥Specify a MySQL data source

在此示例中,目标数据库可使用以下凭据:

¥In this example, the target database is available with the following credentials:

  • 用户:johndoe

    ¥User: johndoe

  • 密码:mypassword

    ¥Password: mypassword

  • 主持人:localhost

    ¥Host: localhost

  • 港口:3306

    ¥Port: 3306

  • 数据库名称:mydb

    ¥Database name: mydb

datasource db {
provider = "mysql"
url = "mysql://johndoe:mypassword@localhost:3306/mydb"
}

了解有关 MySQL 连接字符串 此处 的更多信息。

¥Learn more about MySQL connection strings here.

指定 MongoDB 数据源

¥Specify a MongoDB data source

  • 用户:root

    ¥User: root

  • 密码:password

    ¥Password: password

  • 主持人:cluster1.test1.mongodb.net

    ¥Host: cluster1.test1.mongodb.net

  • 港口:不适用

    ¥Port: N/A

  • 数据库名称:testing

    ¥Database name: testing

datasource db {
provider = "mongodb"
url = "mongodb+srv://root:password@cluster1.test1.mongodb.net/testing?retryWrites=true&w=majority"
}

了解有关 MongoDB 连接字符串 此处 的更多信息。

¥Learn more about MongoDB connection strings here.

指定 SQLite 数据源

¥Specify a SQLite data source

在此示例中,目标数据库位于名为 dev.db 的文件中:

¥In this example, the target database is located in a file called dev.db:

datasource db {
provider = "sqlite"
url = "file:./dev.db"
}

了解有关 SQLite 连接字符串 此处 的更多信息。

¥Learn more about SQLite connection strings here.

指定 CockroachDB 数据源

¥Specify a CockroachDB data source

在此示例中,目标数据库可使用以下凭据:

¥In this example, the target database is available with the following credentials:

  • 用户:johndoe

    ¥User: johndoe

  • 密码:mypassword

    ¥Password: mypassword

  • 主持人:localhost

    ¥Host: localhost

  • 港口:26257

    ¥Port: 26257

  • 数据库名称:mydb

    ¥Database name: mydb

  • 架构名称:public

    ¥Schema name: public

datasource db {
provider = "cockroachdb"
url = "postgresql://johndoe:mypassword@localhost:26257/mydb?schema=public"
}

连接字符串的格式与 PostgreSQL 相同。了解有关 PostgreSQL 连接字符串 此处 的更多信息。

¥The format for connection strings is the same as for PostgreSQL. Learn more about PostgreSQL connection strings here.

generator

在 Prisma 模式中定义 generator

¥Defines a generator in the Prisma schema.

prisma-client-js 提供程序的字段

¥Fields for prisma-client-js provider

generator 块接受以下字段:

¥A generator block accepts the following fields:

名称必需的类型描述
provider是的字符串(文件路径)或 prisma-client-js描述要使用的 generator。这可以指向实现生成器的文件或直接指定内置生成器。
output不*字符串(文件路径)确定生成的客户端 了解更多 的位置。默认:node_modules/.prisma/client
previewFeatures枚举列表使用 intellisense 查看当前可用的预览功能列表(Visual Studio Code 中的 Ctrl+Space)默认:none
engineType枚举(librarybinary定义要下载和使用的 查询引擎 类型。默认:library
binaryTargets枚举列表(见下文)指定 Prisma 客户端将在其上运行的操作系统,以确保 查询引擎 的兼容性。默认:native
moduleFormat枚举(cjsesm定义生成的 Prisma 客户端的模块格式。此字段仅适用于 prisma-client 生成器。
重要

我们建议定义自定义输出路径,将路径添加到 .gitignore,然后确保通过自定义构建脚本或安装后钩子运行 prisma generate

¥We recommend defining a custom output path, adding the path to .gitignore, and then making sure to run prisma generate via a custom build script or postinstall hook.

prisma-client 提供程序的字段(抢先体验版)

¥Fields for prisma-client provider (Early Access)

generator 块接受以下字段:

¥A generator block accepts the following fields:

名称必需的类型描述
provider是的字符串(文件路径)或 prisma-client描述要使用的 generator。这可以指向实现生成器的文件或直接指定内置生成器。
output是的字符串(文件路径)确定生成的客户端 了解更多 的位置。
previewFeatures枚举列表使用 intellisense 查看当前可用的预览功能列表(Visual Studio Code 中的 Ctrl+Space)默认:none
runtime枚举 (nodejs(别名 node)、denobundeno-deployworkerd(别名 cloudflare)、edge-light(别名 vercel)、react-native)目标运行时环境。默认:nodejs
moduleFormat枚举(esmcjs确定生成的代码是否支持 ESM(使用 import)或 CommonJS(使用 require(...))模块。除非你有充分的理由使用 cjs,否则我们始终推荐使用 esm。默认:从环境中推断。
generatedFileExtension枚举 (tsmtscts)生成的 TypeScript 文件的文件扩展名。默认:ts
importFileExtension枚举 (tsmtsctsjsmjscjs,空(用于裸导入))导入语句中使用的文件扩展名默认值:从环境中推断。

binaryTargets 选项

¥binaryTargets options

下表列出了所有受支持的操作系统以及要在 binaryTargets 中指定的平台名称。

¥The following tables list all supported operating systems with the name of platform to specify in binaryTargets.

除非另有说明,默认支持的 CPU 架构为 x86_64。

¥Unless specified otherwise, the default supported CPU architecture is x86_64.

苹果系统

¥macOS

构建操作系统Prisma 引擎构建名称
macOS 英特尔 x86_64darwin
macOS ARM64darwin-arm64
视窗

¥Windows

构建操作系统Prisma 引擎构建名称
视窗windows
Linux(x86_64 架构上的 Alpine)

¥Linux (Alpine on x86_64 architectures)

构建操作系统Prisma 引擎构建名称开放式 SSL
Alpine(3.17 及更高版本)linux-musl-openssl-3.0.x*3.0.x
Alpine(3.16 及以上)linux-musl1.1.x
  • 适用于 Prisma ORM 版本 4.8.0 及更高版本。

¥* Available in Prisma ORM versions 4.8.0 and later.

Linux(ARM64 架构上的 Alpine)

¥Linux (Alpine on ARM64 architectures)

构建操作系统Prisma 引擎构建名称开放式 SSL
Alpine(3.17 及更高版本)linux-musl-arm64-openssl-3.0.x*3.0.x
Alpine(3.16 及以上)linux-musl-arm64-openssl-1.1.x*1.1.x
  • 适用于 Prisma ORM 版本 4.10.0 及更高版本。

¥* Available in Prisma ORM versions 4.10.0 and later.

Linux(Debian),x86_64
构建操作系统Prisma 引擎构建名称开放式 SSL
Debian 8 (Jessie)debian-openssl-1.0.x1.0.x
Debian 9 (Stretch)debian-openssl-1.1.x1.1.x
Debian 10 (Buster)debian-openssl-1.1.x1.1.x
Debian 11 (Bullseye)debian-openssl-1.1.x1.1.x
Debian 12 (Bookworm)debian-openssl-3.0.x3.0.x
Linux(Ubuntu),x86_64
构建操作系统Prisma 引擎构建名称开放式 SSL
Ubuntu 14.04(值得信赖)debian-openssl-1.0.x1.0.x
Ubuntu 16.04(xenial)debian-openssl-1.0.x1.0.x
Ubuntu 18.04(仿生)debian-openssl-1.1.x1.1.x
Ubuntu 19.04(迪斯科)debian-openssl-1.1.x1.1.x
Ubuntu 20.04(焦点)debian-openssl-1.1.x1.1.x
Ubuntu 21.04(多毛)debian-openssl-1.1.x1.1.x
Ubuntu 22.04(杰米)debian-openssl-3.0.x3.0.x
Ubuntu 23.04(农历)debian-openssl-3.0.x3.0.x
Linux(CentOS),x86_64
构建操作系统Prisma 引擎构建名称开放式 SSL
操作系统 7rhel-openssl-1.0.x1.0.x
CentOS 8rhel-openssl-1.1.x1.1.x
Linux (Fedora)、x86_64
构建操作系统Prisma 引擎构建名称开放式 SSL
软呢帽 28rhel-openssl-1.1.x1.1.x
软呢帽 29rhel-openssl-1.1.x1.1.x
软呢帽 30rhel-openssl-1.1.x1.1.x
软呢帽 36rhel-openssl-3.0.x3.0.x
软呢帽 37rhel-openssl-3.0.x3.0.x
软呢帽 38rhel-openssl-3.0.x3.0.x
Linux(Linux Mint),x86_64
构建操作系统Prisma 引擎构建名称开放式 SSL
Linux 薄荷 18debian-openssl-1.0.x1.0.x
Linux 薄荷 19debian-openssl-1.1.x1.1.x
Linux 薄荷 20debian-openssl-1.1.x1.1.x
Linux 薄荷 21debian-openssl-3.0.x3.0.x
Linux(Arch Linux),x86_64
构建操作系统Prisma 引擎构建名称开放式 SSL
Arch Linux 2019.09.01debian-openssl-1.1.x1.1.x
Arch Linux 2023.04.23debian-openssl-3.0.x3.0.x
Linux ARM64(除 Alpine 之外的所有主要发行版)

¥Linux ARM64 (all major distros but Alpine)

构建操作系统Prisma 引擎构建名称开放式 SSL
基于 Linux ARM64 glibc 的发行版linux-arm64-openssl-1.0.x1.0.x
基于 Linux ARM64 glibc 的发行版linux-arm64-openssl-1.1.x1.1.x
基于 Linux ARM64 glibc 的发行版linux-arm64-openssl-3.0.x3.0.x

示例

¥Examples

指定 prisma-client-js 生成器,默认为 outputpreviewFeaturesengineTypebinaryTargets

¥Specify the prisma-client-js generator with the default output, previewFeatures, engineType and binaryTargets

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

请注意,上面的 generator 定义等效于以下定义,因为它使用 outputengineTypebinaryTargets(以及隐式 previewFeatures)的默认值:

¥Note that the above generator definition is equivalent to the following because it uses the default values for output, engineType and binaryTargets (and implicitly previewFeatures):

generator client {
provider = "prisma-client-js"
output = "node_modules/.prisma/client"
engineType = "library"
binaryTargets = ["native"]
}

为 Prisma 客户端指定自定义 output 位置

¥Specify a custom output location for Prisma Client

此示例演示如何定义生成资源的自定义 output 位置以覆盖默认位置。

¥This example shows how to define a custom output location of the generated asset to override the default one.

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

指定自定义 binaryTargets 以确保与操作系统的兼容性

¥Specify custom binaryTargets to ensure compatibility with the OS

此示例显示如何根据表 above 配置 Prisma Client 在 Ubuntu 19.04 (disco) 上运行。

¥This example shows how to configure Prisma Client to run on Ubuntu 19.04 (disco) based on the table above.

generator client {
provider = "prisma-client-js"
binaryTargets = ["debian-openssl-1.1.x"]
}

指定 provider 指向某个自定义生成器实现

¥Specify a provider pointing to some custom generator implementation

此示例演示如何使用位于名为 my-generator 的目录中的自定义生成器。

¥This example shows how to use a custom generator that's located in a directory called my-generator.

generator client {
provider = "./my-generator"
}

model

定义 Prisma model

¥Defines a Prisma model .

备注

¥Remarks

  • 模型的每条记录都必须是唯一可识别的。你必须为每个模型至少定义以下属性之一:

    ¥Every record of a model must be uniquely identifiable. You must define at least one of the following attributes per model:

命名约定

¥Naming conventions

  • 模型名称必须遵循以下正则表达式:[A-Za-z][A-Za-z0-9_]*

    ¥Model names must adhere to the following regular expression: [A-Za-z][A-Za-z0-9_]*

  • 型号名称必须以字母开头,通常拼写为 PascalCase

    ¥Model names must start with a letter and are typically spelled in PascalCase

  • 型号名称应使用单数形式(例如,User 而不是 userusersUsers

    ¥Model names should use the singular form (for example, User instead of user, users or Users)

  • Prisma ORM 有许多保留字正在 Prisma ORM 内部使用,因此不能用作模型名称。你可以找到保留字 此处此处

    ¥Prisma ORM has a number of reserved words that are being used by Prisma ORM internally and therefore cannot be used as a model name. You can find the reserved words here and here.

注意:你可以使用 @@map 属性 将模型(例如 User)映射到具有与模型命名约定不匹配的不同名称(例如 users)的表。

¥Note: You can use the @@map attribute to map a model (for example, User) to a table with a different name that does not match model naming conventions (for example, users).

字段顺序

¥Order of fields

  • 在版本 2.3.0 及更高版本中,内省以与数据库中相应列相同的顺序列出模型字段。关系字段列在标量字段之后。

    ¥In version 2.3.0 and later, introspection lists model fields in the same order as the corresponding columns in the database. Relation fields are listed after scalar fields.

示例

¥Examples

名为 User 的模型,具有两个标量场

¥A model named User with two scalar fields

model User {
email String @unique // `email` can not be optional because it's the only unique field on the model
name String?
}

model 字段

¥model fields

字段 是模型的属性。

¥Fields are properties of models.

备注

¥Remarks

命名约定

¥Naming conventions

  • 必须以字母开头

    ¥Must start with a letter

  • 通常以驼峰命名法拼写

    ¥Typically spelled in camelCase

  • 必须遵守以下正则表达式:[A-Za-z][A-Za-z0-9_]*

    ¥Must adhere to the following regular expression: [A-Za-z][A-Za-z0-9_]*

注意:你可以使用 @map 属性将字段名称映射到列 与不符合字段命名约定的不同名称:例如 myField @map("my_field")

¥Note: You can use the @map attribute to map a field name to a column with a different name that does not match field naming conventions: e.g. myField @map("my_field").

model 字段标量类型

¥model field scalar types

数据源连接器确定每个 Prisma ORM 标量类型映射到的原生数据库类型。类似地,生成器确定这些类型中的每一个映射到目标编程语言中的什么类型。

¥The data source connector determines what native database type each of Prisma ORM scalar type maps to. Similarly, the generator determines what type in the target programming language each of these types map to.

Prisma 模型还具有定义模型之间关系的 模型字段类型

¥Prisma models also have model field types that define relations between models.

String

可变长度文本。

¥Variable length text.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLtext
SQL Servernvarchar(1000)
MySQLvarchar(191)
MongoDBString
SQLiteTEXT
CockroachDBSTRING

PostgreSQL

原生数据库类型原生数据库类型属性注意
text@db.Text
char(x)@db.Char(x)
varchar(x)@db.VarChar(x)
bit(x)@db.Bit(x)
varbit@db.VarBit
uuid@db.Uuid
xml@db.Xml
inet@db.Inet
citext@db.Citext仅当 Citext 扩展已启用 时可用。

MySQL

原生数据库类型原生数据库类型属性
VARCHAR(x)@db.VarChar(x)
TEXT@db.Text
CHAR(x)@db.Char(x)
TINYTEXT@db.TinyText
MEDIUMTEXT@db.MediumText
LONGTEXT@db.LongText

你可以使用 Prisma Migrate 将 @db.Bit(1) 映射到 String

¥You can use Prisma Migrate to map @db.Bit(1) to String:

model Model {
/* ... */
myField String @db.Bit(1)
}

MongoDB

String

原生数据库类型属性注意
@db.String
@db.ObjectId如果基础 BSON 类型为 OBJECT_ID(ID 字段、关系标量),则为必需

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性
char(x)@db.Char(x)
nchar(x)@db.NChar(x)
varchar(x)@db.VarChar(x)
nvarchar(x)@db.NVarChar(x)
text@db.Text
ntext@db.NText
xml@db.Xml
uniqueidentifier@db.UniqueIdentifier

SQLite

TEXT

CockroachDB

原生数据库类型原生数据库类型属性注意
STRING(x) | TEXT(x) | VARCHAR(x)@db.String(x)
CHAR(x)@db.Char(x)
"char"@db.CatalogSingleChar
BIT(x)@db.Bit(x)
VARBIT@db.VarBit
UUID@db.Uuid
INET@db.Inet

请注意,目前 CockroachDB 不支持 PostgreSQL 中支持的 xmlcitext 类型。

¥Note that the xml and citext types supported in PostgreSQL are not currently supported in CockroachDB.

客户端

¥Clients

Prisma 客户端 JS
string

Boolean

真值或假值。

¥True or false value.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLboolean
SQL Serverbit
MySQLTINYINT(1)
MongoDBBool
SQLiteINTEGER
CockroachDBBOOL

PostgreSQL

原生数据库类型原生数据库类型属性注意
boolean@db.Boolean

MySQL

原生数据库类型原生数据库类型属性注意
TINYINT(1)@db.TinyInt(1)如果最大长度大于 1(例如 TINYINT(2))或默认值不是 10NULL,则 TINYINT 映射到 Int
BIT(1)@db.Bit

MongoDB

Bool

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性注意
bit@db.Bit

SQLite

INTEGER

CockroachDB

原生数据库类型原生数据库类型属性注意
BOOL@db.Bool

客户端

¥Clients

Prisma 客户端 JS
boolean

Int

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLinteger
SQL Serverint
MySQLINT
MongoDBInt
SQLiteINTEGER
CockroachDBINT

PostgreSQL

原生数据库类型原生数据库类型属性注意
integer | int, int4@db.Integer
smallint | int2@db.SmallInt
smallserial | serial2@db.SmallInt @default(autoincrement())
serial | serial4@db.Int @default(autoincrement())
oid@db.Oid

MySQL

原生数据库类型原生数据库类型属性注意
INT@db.Int
INT UNSIGNED@db.UnsignedInt
SMALLINT@db.SmallInt
SMALLINT UNSIGNED@db.UnsignedSmallInt
MEDIUMINT@db.MediumInt
MEDIUMINT UNSIGNED@db.UnsignedMediumInt
TINYINT@db.TinyInt如果最大长度大于 1(例如 TINYINT(2))或默认值不是 10NULL,则 TINYINT 映射到 IntTINYINT(1) 映射到 Boolean
TINYINT UNSIGNED@db.UnsignedTinyIntTINYINT(1) UNSIGNED 映射到 Int,而不是 Boolean
YEAR@db.Year

MongoDB

Int

原生数据库类型属性注意
@db.Int
@db.Long

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性注意
int@db.Int
smallint@db.SmallInt
tinyint@db.TinyInt
bit@db.Bit

SQLite

INTEGER

CockroachDB

原生数据库类型原生数据库类型属性注意
INTEGER | INT | INT8@db.Int8请注意,这与 PostgreSQL 不同,其中 integerintint4 的别名并映射到 @db.Integer
INT4@db.Int4
INT2 | SMALLINT@db.Int2
SMALLSERIAL | SERIAL2@db.Int2 @default(autoincrement())
SERIAL | SERIAL4@db.Int4 @default(autoincrement())
SERIAL8 | BIGSERIAL@db.Int8 @default(autoincrement())

客户端

¥Clients

Prisma 客户端 JS
number

BigInt

BigInt2.17.0 及更高版本中可用。

¥BigInt is available in version 2.17.0 and later.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLbigint
SQL Serverint
MySQLBIGINT
MongoDBLong
SQLiteINTEGER
CockroachDBINTEGER

PostgreSQL

原生数据库类型原生数据库类型属性注意
bigint | int8@db.BigInt
bigserial | serial8@db.BigInt @default(autoincrement())

MySQL

原生数据库类型原生数据库类型属性注意
BIGINT@db.BigInt
SERIAL@db.UnsignedBigInt @default(autoincrement())

MongoDB

Long

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性注意
bigint@db.BigInt

SQLite

INTEGER

CockroachDB

原生数据库类型原生数据库类型属性注意
BIGINT | INT | INT8@db.Int8请注意,这与 PostgreSQL 不同,其中 intint4 的别名
bigserial | serial8@db.Int8 @default(autoincrement())

客户端

¥Clients

客户类型描述
Prisma 客户端 JSBigIntBigInt 合作的示例

Float

浮点数。

¥Floating point number.

Float2.17.0 及更高版本中映射到 Double - 有关此更改的更多信息,请参阅 发行说明视频:Prisma ORM 2.17.0 中 Float 默认映射的更改

¥Float maps to Double in 2.17.0 and later - see release notes and Video: Changes to the default mapping of Float in Prisma ORM 2.17.0 for more information about this change.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLdouble precision
SQL Serverfloat(53)
MySQLDOUBLE
MongoDBDouble
SQLiteREAL
CockroachDBDOUBLE PRECISION

PostgreSQL

原生数据库类型原生数据库类型属性注意
double precision@db.DoublePrecision
real@db.Real

MySQL

原生数据库类型原生数据库类型属性注意
FLOAT@db.Float
DOUBLE@db.Double

MongoDB

Double

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性
float@db.Float
money@db.Money
smallmoney@db.SmallMoney
real@db.Real

SQLite 连接器

¥SQLite connector

REAL

CockroachDB

原生数据库类型原生数据库类型属性注意
DOUBLE PRECISION | FLOAT8@db.Float8
REAL | FLOAT4 | FLOAT@db.Float4

客户端

¥Clients

Prisma 客户端 JS
number

Decimal

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLdecimal(65,30)
SQL Serverdecimal(32,16)
MySQLDECIMAL(65,30)
MongoDB不支持
SQLiteDECIMAL
CockroachDBDECIMAL

PostgreSQL

原生数据库类型原生数据库类型属性注意
decimal | numeric@db.Decimal(p, s)
money@db.Money
  • p(精度),要存储的最大小数位数。s(小数位数),小数点右侧存储的小数位数。

    ¥† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.

MySQL

原生数据库类型原生数据库类型属性注意
DECIMAL | NUMERIC@db.Decimal(p, s)
  • p(精度),要存储的最大小数位数。s(小数位数),小数点右侧存储的小数位数。

    ¥† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.

MongoDB

不支持

¥Not supported.

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性注意
decimal | numeric@db.Decimal(p, s)
  • p(精度),要存储的最大小数位数。s(小数位数),小数点右侧存储的小数位数。

    ¥† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.

SQLite

DECIMAL(2.17.0 中由 REAL 更改)

¥DECIMAL (changed from REAL in 2.17.0)

CockroachDB

原生数据库类型原生数据库类型属性注意
DECIMAL | DEC | NUMERIC@db.Decimal(p, s)
money还没有CockroachDB 尚不支持 PostgreSQL 的 money 类型
  • p(精度),要存储的最大小数位数。s(小数位数),小数点右侧存储的小数位数。

    ¥† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.

客户端

¥Clients

客户类型描述
Prisma 客户端 JSDecimalDecimal 合作的示例

DateTime

备注

¥Remarks

  • Prisma 客户端将所有 DateTime 作为原生 Date 对象返回。

    ¥Prisma Client returns all DateTime as native Date objects.

  • 目前,MySQL 中的 Prisma ORM 不支持支持 零日期0000-00-00 00:00:000000-00-0000:00:00)。

    ¥Currently, Prisma ORM does not support zero dates (0000-00-00 00:00:00, 0000-00-00, 00:00:00) in MySQL.

  • 目前有一个 bug,它不允许你将 DateTime 值作为字符串传递,并且在你这样做时会产生运行时错误。DateTime 值需要作为 Date 对象传递(即 new Date('2024-12-04') 而不是 '2024-12-04')。

    ¥There currently is a bug that doesn't allow you to pass in DateTime values as strings and produces a runtime error when you do. DateTime values need to be passed as Date objects (i.e. new Date('2024-12-04') instead of '2024-12-04').

你可以在本节中找到更多信息和示例:DateTime 合作

¥You can find more info and examples in this section: Working with DateTime.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLtimestamp(3)
SQL Serverdatetime2
MySQLDATETIME(3)
MongoDBTimestamp
SQLiteNUMERIC
CockroachDBTIMESTAMP

PostgreSQL

原生数据库类型原生数据库类型属性注意
timestamp(x)@db.Timestamp(x)
timestamptz(x)@db.Timestamptz(x)
date@db.Date
time(x)@db.Time(x)
timetz(x)@db.Timetz(x)

MySQL

原生数据库类型原生数据库类型属性注意
DATETIME(x)@db.DateTime(x)
DATE(x)@db.Date(x)
TIME(x)@db.Time(x)
TIMESTAMP(x)@db.Timestamp(x)

你还可以将 MySQL 的 YEAR 类型与 Int 一起使用:

¥You can also use MySQL's YEAR type with Int:

yearField     Int    @db.Year

MongoDB

Timestamp

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性注意
date@db.Date
time@db.Time
datetime@db.DateTime
datetime2@db.DateTime2
smalldatetime@db.SmallDateTime
datetimeoffset@db.DateTimeOffset

SQLite

NUMERICSTRING。如果基础数据类型为 STRING,则必须使用以下格式之一:

¥NUMERIC or STRING. If the underlying data type is STRING, you must use one of the following formats:

CockroachDB

原生数据库类型原生数据库类型属性注意
TIMESTAMP(x)@db.Timestamp(x)
TIMESTAMPTZ(x)@db.Timestamptz(x)
DATE@db.Date
TIME(x)@db.Time(x)
TIMETZ(x)@db.Timetz(x)

客户端

¥Clients

Prisma 客户端 JS
Date

Json

一个 JSON 对象。

¥A JSON object.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLjsonb
SQL Server不支持
MySQLJSON
MongoDB有效的 BSON 对象(宽松模式)
SQLiteJSONB
CockroachDBJSONB

PostgreSQL

原生数据库类型原生数据库类型属性注意
json@db.Json
jsonb@db.JsonB

MySQL

原生数据库类型原生数据库类型属性注意
JSON@db.Json

MongoDB

有效的 BSON 对象(宽松模式)

¥A valid BSON object (Relaxed mode)

微软 SQL 服务器

¥Microsoft SQL Server

Microsoft SQL Server 没有 JSON 的特定数据类型。但是,用于读取和修改 JSON 的内置函数 有多个。

¥Microsoft SQL Server does not have a specific data type for JSON. However, there are a number of built-in functions for reading and modifying JSON.

SQLite

不支持

¥Not supported

CockroachDB

原生数据库类型原生数据库类型属性注意
JSON | JSONB@db.JsonB

客户端

¥Clients

Prisma 客户端 JS
object

Bytes

Bytes2.17.0 及更高版本中可用。

¥Bytes is available in version 2.17.0 and later.

默认类型映射

¥Default type mappings

连接器默认映射
PostgreSQLbytea
SQL Servervarbinary
MySQLLONGBLOB
MongoDBBinData
SQLiteBLOB
CockroachDBBYTES

PostgreSQL

原生数据库类型原生数据库类型属性
bytea@db.ByteA

MySQL

原生数据库类型原生数据库类型属性注意
LONGBLOB@db.LongBlob
BINARY@db.Binary
VARBINARY@db.VarBinary
TINYBLOB@db.TinyBlob
BLOB@db.Blob
MEDIUMBLOB@db.MediumBlob
BIT@db.Bit

MongoDB

BinData

原生数据库类型属性注意
@db.ObjectId如果基础 BSON 类型为 OBJECT_ID(ID 字段、关系标量),则为必需
@db.BinData

微软 SQL 服务器

¥Microsoft SQL Server

原生数据库类型原生数据库类型属性注意
binary@db.Binary
varbinary@db.VarBinary
image@db.Image

SQLite

BLOB

CockroachDB

原生数据库类型原生数据库类型属性
BYTES | BYTEA | BLOB@db.Bytes

客户端

¥Clients

客户类型描述
Prisma 客户端 JSUint8ArrayBytes 合作的示例
Prisma Client JS (v6 之前)BufferBytes 合作的示例

Unsupported

warning

MongoDB 不支持
MongoDB 连接器 不支持 Unsupported 类型。

¥Not supported by MongoDB
The MongoDB connector does not support the Unsupported type.

Unsupported 类型是在 2.17.0 中引入的,允许你表示 Prisma 架构中 Prisma 客户端不支持的数据类型。类型 Unsupported 的字段可以在自省期间使用 prisma db pull 创建或手动写入,并使用 Prisma Migrate 或 db push 在数据库中创建。

¥The Unsupported type was introduced in 2.17.0 and allows you to represent data types in the Prisma schema that are not supported by Prisma Client. Fields of type Unsupported can be created during Introspection with prisma db pull or written by hand, and created in the database with Prisma Migrate or db push.

备注

¥Remarks

  • Unsupported 类型的字段在生成的客户端中不可用。

    ¥Fields with Unsupported types are not available in the generated client.

  • 如果模型包含所需的 Unsupported 类型,则 prisma.model.create(..)prisma.model.update(...)prisma.model.upsert(...) 在 Prisma Client 中不可用。

    ¥If a model contains a required Unsupported type, prisma.model.create(..), prisma.model.update(...) and prisma.model.upsert(...) are not available in Prisma Client.

  • 当你自省包含不支持类型的数据库时,Prisma ORM 将提供以下警告:

    ¥When you introspect a database that contains unsupported types, Prisma ORM will provide the following warning:

    *** WARNING ***

    These fields are not supported by Prisma Client, because Prisma does not currently support their types.

    * Model "Post", field: "circle", original data type: "circle"

示例

¥Examples

model Star {
id Int @id @default(autoincrement())
position Unsupported("circle")?
example1 Unsupported("circle")
circle Unsupported("circle")? @default(dbgenerated("'<(10,4),11>'::circle"))
}

model 字段类型修饰符

¥model field type modifiers

[] 修改器

¥[] modifier

将字段设为列表。

¥Makes a field a list.

备注

¥Remarks

  • 不能是可选的(例如 Post[]?)。

    ¥Cannot be optional (for example Post[]?).

关系数据库

¥Relational databases

  • 仅当你的数据库本身支持标量列表(数组)时,数据模型才支持标量列表(数组)。因此,目前仅在使用 PostgreSQL 或 CockroachDB 时才支持标量列表(因为 MySQL 和 SQLite 本身不支持标量列表)。

    ¥Scalar lists (arrays) are only supported in the data model if your database natively supports them. Currently, scalar lists are therefore only supported when using PostgreSQL or CockroachDB (since MySQL and SQLite don't natively support scalar lists).

MongoDB
  • 支持标量列表

    ¥Scalar lists are supported

示例

¥Examples

定义标量列表

¥Define a scalar list

model User {
id Int @id @default(autoincrement())
favoriteColors String[]
}
定义具有默认值的标量列表

¥Define a scalar list with a default value

在 4.0.0 及更高版本中可用。

¥Available in version 4.0.0 and later.

model User {
id Int @id @default(autoincrement())
favoriteColors String[] @default(["red", "blue", "green"])
}

? 修改器

¥? modifier

使字段可选。

¥Makes a field optional.

备注

¥Remarks

  • 不能与列表字段一起使用(例如,Posts[]

    ¥Cannot be used with a list field (for example, Posts[])

示例

¥Examples

可选 name 字段

¥Optional name field

model User {
id Int @id @default(autoincrement())
name String?
}

属性

¥Attributes

属性修改 field 或块(例如 models)的行为。有两种方法可以将属性添加到数据模型:

¥Attributes modify the behavior of a field or block (e.g. models). There are two ways to add attributes to your data model:

  • 字段属性以 @ 为前缀

    ¥Field attributes are prefixed with @

  • 块属性以 @@ 为前缀

    ¥Block attributes are prefixed with @@

有些属性带有参数。属性中的参数总是被命名,但在大多数情况下参数名称可以省略。

¥Some attributes take arguments. Arguments in attributes are always named, but in most cases the argument name can be omitted.

注意:签名中的前导下划线表示可以省略参数名称。

¥Note: The leading underscore in a signature means the argument name can be omitted.

@id

在模型上定义单字段 ID。

¥Defines a single-field ID on the model.

备注

¥Remarks

一般的

¥General

  • 无法在关系字段上定义

    ¥Cannot be defined on a relation field

  • 不能是可选的

    ¥Cannot be optional

关系数据库

¥Relational databases

  • 对应的数据库构造:PRIMARY KEY

    ¥Corresponding database construct: PRIMARY KEY

  • 可以使用 functions 自动生成 ID 的 @default 属性进行注释:

    ¥Can be annotated with a @default attribute that uses functions to auto-generate an ID:

  • 可以在任何标量字段上定义(StringIntenum

    ¥Can be defined on any scalar field (String, Int, enum)

MongoDB
  • 对应的数据库构造:任何有效的 BSON 类型,数组除外

    ¥Corresponding database construct: Any valid BSON type, except arrays

  • 每个模型必须定义一个 @id 字段

    ¥Every model must define an @id field

  • 底层 ID 字段名称始终为 _id,并且必须与 @map("_id") 映射

    ¥The underlying ID field name is always _id, and must be mapped with @map("_id")

  • 可以在任何标量字段(StringIntenum)上定义,除非你想在数据库中使用 ObjectId

    ¥Can be defined on any scalar field (String, Int, enum) unless you want to use ObjectId in your database

  • 要使用 ObjectId 作为你的 ID,你必须:

    ¥To use an ObjectId as your ID, you must:

    • 使用 StringBytes 字段类型

      ¥Use the String or Bytes field type

    • @db.ObjectId 注释你的字段:

      ¥Annotate your field with @db.ObjectId:

      id   String  @db.ObjectId  @map("_id")
    • (可选)使用 @default 属性注释你的字段,该属性使用 auto() 函数 自动生成 ObjectId

      ¥Optionally, annotate your field with a @default attribute that uses the auto() function to auto-generate an ObjectId

      id   String  @db.ObjectId  @map("_id") @default(auto())
  • 支持 cuid()uuid()ulid(),但不生成有效的 ObjectId - 使用 auto() 代替 @id

    ¥cuid(), uuid() and ulid() are supported but do not generate a valid ObjectId - use auto() instead for @id

  • 不支持 autoincrement()

    ¥autoincrement() is not supported

参数

¥Arguments

名称必需的类型描述
mapString数据库中基础主键约束的名称。

MySQL 或 MongoDB 不支持。
lengthnumber允许你指定要索引的值的子部分的最大长度。仅限

MySQL。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
sortString允许你指定 ID 条目在数据库中的存储顺序。可用选项仅限 AscDesc.

SQL Server。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
clusteredBoolean定义 ID 是集群 ID 还是非集群 ID。默认为 true。仅限

SQL Server。在版本 3.13.0 及更高版本中提供预览版,并在版本 4.0.0 及更高版本中提供正式版本。

签名

¥Signature

@id(map: String?, length: number?, sort: String?, clustered: Boolean?)

注意:在版本 4.0.0 或启用 extendedIndexes 预览功能的 3.5.0 之前,签名为:

¥Note: Before version 4.0.0, or 3.5.0 with the extendedIndexes Preview feature enabled, the signature was:

@id(map: String?)

注意:在 3.0.0 版本之前,签名是:

¥Note: Before version 3.0.0, the signature was:

@id

示例

¥Examples

在大多数情况下,你希望数据库创建 ID。为此,请使用 @default 属性注释 ID 字段,并使用 function 初始化该字段。

¥In most cases, you want your database to create the ID. To do this, annotate the ID field with the @default attribute and initialize the field with a function.

生成自动递增整数作为 ID(仅限关系数据库)

¥Generate autoincrementing integers as IDs (Relational databases only)

model User {
id Int @id @default(autoincrement())
name String
}
生成 ObjectId 作为 ID(仅限 MongoDB)

¥Generate ObjectId as IDs (MongoDB only)

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
}
生成 cuid() 值作为 ID

¥Generate cuid() values as IDs

model User {
id String @id @default(cuid())
name String
}
生成 uuid() 值作为 ID

¥Generate uuid() values as IDs

model User {
id String @id @default(uuid())
name String
}
生成 ulid() 值作为 ID

¥Generate ulid() values as IDs

model User {
id String @id @default(ulid())
name String
}
没有默认值的单字段 ID

¥Single-field IDs without default values

在以下示例中,id 没有默认值:

¥In the following example, id does not have a default value:

model User {
id String @id
name String
}

请注意,在上述情况下,使用 Prisma Client 为 User 模型创建新记录时,你必须提供自己的 ID 值,例如:

¥Note that in the above case, you must provide your own ID values when creating new records for the User model using Prisma Client, e.g.:

const newUser = await prisma.user.create({
data: {
id: 1,
name: "Alice",
},
});
在没有默认值的关系标量字段上指定 ID

¥Specify an ID on relation scalar field without a default value

在以下示例中,authorId 既是关系标量,又是 Profile 的 ID:

¥In the following example, authorId is a both a relation scalar and the ID of Profile:

model Profile {
authorId Int @id
author User @relation(fields: [authorId], references: [id])
bio String
}

model User {
id Int @id
email String @unique
name String?
profile Profile?
}

在这种情况下,你不能仅创建 Profile - 你必须使用 Prisma 客户端的 嵌套写入 创建 User 或将配置文件连接到现有用户。

¥In this scenario, you cannot create a Profile only - you must use Prisma Client's nested writes create a User or connect the profile to an existing user.

以下示例创建用户和配置文件:

¥The following example creates a user and a profile:

const userWithProfile = await prisma.user.create({
data: {
id: 3,
email: "bob@prisma.io",
name: "Bob Prismo",
profile: {
create: {
bio: "Hello, I'm Bob Prismo and I love apples, blue nail varnish, and the sound of buzzing mosquitoes.",
},
},
},
});

以下示例将新配置文件连接到用户:

¥The following example connects a new profile to a user:

const profileWithUser = await prisma.profile.create({
data: {
bio: "Hello, I'm Bob and I like nothing at all. Just nothing.",
author: {
connect: {
id: 22,
},
},
},
});

@@id

warning

MongoDB 不支持
MongoDB 连接器 不支持复合 ID。

¥Not supported by MongoDB
The MongoDB connector does not support composite IDs.

在模型上定义多字段 ID(复合 ID)。

¥Defines a multi-field ID (composite ID) on the model.

备注

¥Remarks

  • 对应的数据库类型:PRIMARY KEY

    ¥Corresponding database type: PRIMARY KEY

  • 可以使用 functions 自动生成 ID 的 @default 属性进行注释

    ¥Can be annotated with a @default attribute that uses functions to auto-generate an ID

  • 不能是可选的

    ¥Cannot be optional

  • 可以在任何标量字段上定义(StringIntenum

    ¥Can be defined on any scalar field (String, Int, enum)

  • 无法在关系字段上定义

    ¥Cannot be defined on a relation field

  • Prisma 客户端中的复合 ID 字段的名称具有以下模式:field1_field2_field3

    ¥The name of the composite ID field in Prisma Client has the following pattern: field1_field2_field3

参数

¥Arguments

名称必需的类型描述
fields是的FieldReference[]字段名称列表 - 例如,["firstname", "lastname"]
nameStringPrisma 客户端将为涵盖所有字段的参数公开的名称,例如 fullNamefullName: { firstName: "First", lastName: "Last"}
mapString数据库中基础主键约束的名称。

MySQL 不支持。
lengthnumber允许你指定要索引的值的子部分的最大长度。仅限

MySQL。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
sortString允许你指定 ID 条目在数据库中的存储顺序。可用选项仅限 AscDesc.

SQL Server。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
clusteredBoolean定义 ID 是集群 ID 还是非集群 ID。默认仅适用于 true.

SQL Server。在版本 3.13.0 及更高版本中提供预览版,并在版本 4.0.0 及更高版本中提供正式版本。

@@id 属性上的 fields 参数的名称可以省略:

¥The name of the fields argument on the @@id attribute can be omitted:

@@id(fields: [title, author])
@@id([title, author])

签名

¥Signature

@@id(_ fields: FieldReference[], name: String?, map: String?)

注意:在 3.0.0 版本之前,签名为:

¥Note: Until version 3.0.0, the signature was:

@@id(_ fields: FieldReference[])

示例

¥Examples

在两个 String 字段上指定多字段 ID(仅限关系数据库)

¥Specify a multi-field ID on two String fields (Relational databases only)

model User {
firstName String
lastName String
email String @unique
isAdmin Boolean @default(false)

@@id([firstName, lastName])
}

创建用户时,必须提供 firstNamelastName 的唯一组合:

¥When you create a user, you must provide a unique combination of firstName and lastName:

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

要检索用户,请使用生成的复合 ID 字段 (firstName_lastName):

¥To retrieve a user, use the generated composite ID field (firstName_lastName):

const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: "Alice",
lastName: "Smith",
},
},
});
在两个 String 字段和 1 个 Boolean 字段上指定多字段 ID(仅限关系数据库)

¥Specify a multi-field ID on two String fields and one Boolean field (Relational databases only)

model User {
firstName String
lastName String
email String @unique
isAdmin Boolean @default(false)

@@id([firstName, lastName, isAdmin])
}

创建新的 User 记录时,你现在必须为 firstNamelastNameisAdmin 提供唯一的值组合:

¥When creating new User records, you now must provide a unique combination of values for firstName, lastName and isAdmin:

const user = await prisma.user.create({
data: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
});
指定包含关系字段的多字段 ID(仅限关系数据库)

¥Specify a multi-field ID that includes a relation field (Relational databases only)

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

@@id([authorId, title])
}

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

创建新的 Post 记录时,你现在必须提供 authorId(外键)和 title 值的唯一组合:

¥When creating new Post records, you now must provide a unique combination of values for authorId (foreign key) and title:

const post = await prisma.post.create({
data: {
title: "Hello World",
author: {
connect: {
email: "alice@prisma.io",
},
},
},
});

@default

定义 字段的默认值

¥Defines a default value for a field.

备注

¥Remarks

  • 使用 introspection 时,Prisma 模式中尚无法表示的默认值由 dbgenerated() 功能 表示。

    ¥Default values that cannot yet be represented in the Prisma schema are represented by the dbgenerated() function when you use introspection.

  • Prisma 架构中的关系字段不允许使用默认值。但请注意,你仍然可以在支持关系的字段上定义默认值(在 @relation 属性的 fields 参数中列出的值)。支持关系的字段上的默认值意味着该关系会自动为你填充。

    ¥Default values are not allowed on relation fields in the Prisma schema. Note however that you can still define default values on the fields backing a relation (the ones listed in the fields argument in the @relation attribute). A default value on the field backing a relation will mean that relation is populated automatically for you.

  • 默认值可以与原生支持它们的数据库中的 标量列表 一起使用。

    ¥Default values can be used with scalar lists in databases that natively support them.

关系数据库

¥Relational databases

  • 对应的数据库构造:DEFAULT

    ¥Corresponding database construct: DEFAULT

  • 默认值可以是静态值(4"hello")或以下 functions 之一:

    ¥Default values can be a static value (4, "hello") or one of the following functions:

  • 使用 introspection 时,Prisma 模式中尚无法表示的默认值由 dbgenerated(...) 功能 表示。

    ¥Default values that cannot yet be represented in the Prisma schema are represented by the dbgenerated(...) function when you use introspection.

  • Prisma 架构中的关系字段不允许使用默认值。但请注意,你仍然可以在支持关系的字段上定义默认值(在 @relation 属性的 fields 参数中列出的值)。支持关系的字段上的默认值意味着该关系会自动为你填充。

    ¥Default values are not allowed on relation fields in the Prisma schema. Note however that you can still define default values on the fields backing a relation (the ones listed in the fields argument in the @relation attribute). A default value on the field backing a relation will mean that relation is populated automatically for you.

  • 默认值可以与原生支持它们的数据库中的 标量列表 一起使用。

    ¥Default values can be used with scalar lists in databases that natively support them.

  • JSON 数据。请注意,JSON 需要在 @default 属性内用双引号括起来,例如:@default("[]")。如果你想要提供 JSON 对象,则需要将其用双引号括起来,然后使用反斜杠转义任何内部双引号,例如:@default("{ \"hello\": \"world\" }")

    ¥JSON data. Note that JSON needs to be enclosed with double-quotes inside the @default attribute, e.g.: @default("[]"). If you want to provide a JSON object, you need to enclose it with double-quotes and then escape any internal double quotes using a backslash, e.g.: @default("{ \"hello\": \"world\" }").

MongoDB
  • 默认值可以是静态值(4"hello")或以下 functions 之一:

    ¥Default values can be a static value (4, "hello") or one of the following functions:

    • auto()(只能与 @db.ObjectId 一起使用在 MongoDB 中生成 ObjectId

      ¥auto() (can only be used with @db.ObjectId to generate an ObjectId in MongoDB)

    • cuid()

    • uuid()

    • ulid()

    • now()

参数

¥Arguments

名称必需的类型描述
value是的表达式(例如 5truenow()
map字符串仅限 SQL Server。

@default 属性上的 value 参数的名称可以省略:

¥The name of the value argument on the @default attribute can be omitted:

id Int @id @default(value: autoincrement())
id Int @id @default(autoincrement())

签名

¥Signature

@default(_ value: Expression, map: String?)

注意:在 3.0.0 版本之前,签名为:

¥Note: Until version 3.0.0, the signature was:

@default(_ value: Expression)

示例

¥Examples

Int 的默认值

¥Default value for an Int

model User {
email String @unique
profileViews Int @default(0)
}
Float 的默认值

¥Default value for a Float

model User {
email String @unique
number Float @default(1.1)
}
Decimal 的默认值

¥Default value for Decimal

model User {
email String @unique
number Decimal @default(22.99)
}
BigInt 的默认值

¥Default value for BigInt

model User {
email String @unique
number BigInt @default(34534535435353)
}
String 的默认值

¥Default value for a String

model User {
email String @unique
name String @default("")
}
Boolean 的默认值

¥Default value for a Boolean

model User {
email String @unique
isAdmin Boolean @default(false)
}
DateTime 的默认值

¥Default value for a DateTime

请注意,DateTime 的静态默认值基于 ISO 8601 标准。

¥Note that static default values for DateTime are based on the ISO 8601 standard.

model User {
email String @unique
data DateTime @default("2020-03-19T14:21:00+02:00")
}
Bytes 的默认值

¥Default value for a Bytes

model User {
email String @unique
secret Bytes @default("SGVsbG8gd29ybGQ=")
}
enum 的默认值

¥Default value for an enum

enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
role Role @default(USER)
posts Post[]
profile Profile?
}
标量列表的默认值

¥Default values for scalar lists

model User {
id Int @id @default(autoincrement())
posts Post[]
favoriteColors String[] @default(["red", "yellow", "purple"])
roles Role[] @default([USER, DEVELOPER])
}

enum Role {
USER
DEVELOPER
ADMIN
}

@unique

为此字段定义唯一约束。

¥Defines a unique constraint for this field.

备注

¥Remarks

一般的

¥General

  • @unique 注释的字段可以是可选的或必需的

    ¥A field annotated with @unique can be optional or required

  • 如果用 @unique 注释的字段表示没有 @id / @@id 的模型上的唯一唯一约束,则必须需要该字段

    ¥A field annotated with @unique must be required if it represents the only unique constraint on a model without an @id / @@id

  • 模型可以有任意数量的唯一约束

    ¥A model can have any number of unique constraints

  • 可以在任何标量场上定义

    ¥Can be defined on any scalar field

  • 无法在关系字段上定义

    ¥Cannot be defined on a relation field

关系数据库

¥Relational databases

  • 对应的数据库构造:UNIQUE

    ¥Corresponding database construct: UNIQUE

  • NULL 值被认为是不同的(允许多行在同一列中包含 NULL 值)

    ¥NULL values are considered to be distinct (multiple rows with NULL values in the same column are allowed)

  • 添加唯一约束会自动将相应的唯一索引添加到指定的列。

    ¥Adding a unique constraint automatically adds a corresponding unique index to the specified column(s).

MongoDB

参数

¥Arguments

名称必需的类型描述
mapString
lengthnumber允许你指定要索引的值的子部分的最大长度。仅限

MySQL。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
sortString允许你指定约束条目在数据库中的存储顺序。可用选项为 AscDesc

在 3.5.0 及更高版本中预览,在 4.0.0 及更高版本中全面可用。
clusteredBoolean定义约束是集群约束还是非集群约束。默认仅适用于 false.

SQL Server。在版本 3.13.0 及更高版本中提供预览版,并在版本 4.0.0 及更高版本中提供正式版本。
  • ¹ 某些索引和字段类型可能需要。

    ¥¹ Can be required by some of the index and field types.

签名

¥Signature

@unique(map: String?, length: number?, sort: String?)

注意:在版本 4.0.0 或启用 extendedIndexes 预览功能的 3.5.0 之前,签名为:

¥Note: Before version 4.0.0, or 3.5.0 with the extendedIndexes Preview feature enabled, the signature was:

@unique(map: String?)

注意:在 3.0.0 版本之前,签名是:

¥Note: Before version 3.0.0, the signature was:

@unique

示例

¥Examples

在必填 String 字段上指定唯一属性

¥Specify a unique attribute on a required String field

model User {
email String @unique
name String
}
在可选的 String 字段上指定唯一属性

¥Specify a unique attribute on an optional String field

model User {
id Int @id @default(autoincrement())
email String? @unique
name String
}
在关系标量字段 authorId 上指定唯一属性

¥Specify a unique attribute on relation scalar field authorId

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

model User {
id Int @id @default(autoincrement())
email String? @unique
name String
Post Post[]
}
指定一个唯一属性,并将 cuid() 值作为默认值

¥Specify a unique attribute with cuid() values as default values

model User {
token String @unique @default(cuid())
name String
}

@@unique

为指定字段定义复合 唯一约束

¥Defines a compound unique constraint for the specified fields.

备注

¥Remarks

一般的

¥General

  • 构成唯一约束的所有字段都必须是必填字段。以下模型无效,因为 id 可能是 null

    ¥All fields that make up the unique constraint must be mandatory fields. The following model is not valid because id could be null:

    model User {
    firstname Int
    lastname Int
    id Int?

    @@unique([firstname, lastname, id])
    }

    出现此行为的原因是所有连接器都认为 null 值是不同的,这意味着看起来相同的两行被认为是唯一的:

    ¥The reason for this behavior is that all connectors consider null values to be distinct, which means that two rows that look identical are considered unique:

     firstname  | lastname | id
    -----------+----------+------
    John | Smith | null
    John | Smith | null
  • 一个模型可以有任意数量的 @@unique

    ¥A model can have any number of @@unique blocks

关系数据库

¥Relational databases

  • 对应的数据库构造:UNIQUE

    ¥Corresponding database construct: UNIQUE

  • 如果 @@unique 块代表模型上唯一的唯一约束而没有 @id / @@id,则需要 @@unique

    ¥A @@unique block is required if it represents the only unique constraint on a model without an @id / @@id

  • 添加唯一约束会自动将相应的唯一索引添加到指定列

    ¥Adding a unique constraint automatically adds a corresponding unique index to the specified column(s)

MongoDB
  • MongoDB 中的复合索引 强制执行

    ¥Enforced by a compound index in MongoDB

  • @@unique 块不能用作模型的唯一唯一标识符 - MongoDB 需要 @id 字段

    ¥A @@unique block cannot be used as the only unique identifier for a model - MongoDB requires an @id field

参数

¥Arguments

名称必需的类型描述
fields是的FieldReference[]字段名称列表 - 例如,["firstname", "lastname"]。字段必须为必填项 - 见备注。
nameString字段唯一组合的名称 - 默认为 fieldName1_fieldName2_fieldName3
mapString
lengthnumber允许你指定要索引的值的子部分的最大长度。仅限

MySQL。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
sortString允许你指定约束条目在数据库中的存储顺序。可用选项为 AscDesc

在 3.5.0 及更高版本中预览,在 4.0.0 及更高版本中全面可用。
clusteredBoolean定义约束是集群约束还是非集群约束。默认仅适用于 false.

SQL Server。在版本 3.13.0 及更高版本中提供预览版,并在版本 4.0.0 及更高版本中提供正式版本。

@@unique 属性上的 fields 参数的名称可以省略:

¥The name of the fields argument on the @@unique attribute can be omitted:

@@unique(fields: [title, author])
@@unique([title, author])
@@unique(fields: [title, author], name: "titleAuthor")

lengthsort 参数被添加到相关字段名称中:

¥The length and sort arguments are added to the relevant field names:

@@unique(fields: [title(length:10), author])
@@unique([title(sort: Desc), author(sort: Asc)])

签名

¥Signature

@@unique(_ fields: FieldReference[], name: String?, map: String?)

注意:在版本 4.0.0 之前,或在启用了 extendedIndexes Preview 功能的版本 3.5.0 之前,签名为:

¥Note: Before version 4.0.0, or before version 3.5.0 with the extendedIndexes Preview feature enabled, the signature was:

@@unique(_ fields: FieldReference[], name: String?, map: String?)

注意:在 3.0.0 版本之前,签名是:

¥Note: Before version 3.0.0, the signature was:

@@unique(_ fields: FieldReference[], name: String?)

示例

¥Examples

在两个 String 字段上指定多字段唯一属性

¥Specify a multi-field unique attribute on two String fields

model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)

@@unique([firstName, lastName])
}

要检索用户,请使用生成的字段名称 (firstname_lastname):

¥To retrieve a user, use the generated field name (firstname_lastname):

const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
},
});
在两个 String 字段和一个 Boolean 字段上指定多字段唯一属性

¥Specify a multi-field unique attribute on two String fields and one Boolean field

model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)

@@unique([firstName, lastName, isAdmin])
}
指定包含关系字段的多字段唯一属性

¥Specify a multi-field unique attribute that includes a relation field

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

@@unique([authorId, title])
}

model User {
id Int @id @default(autoincrement())
email String @unique
posts Post[]
}
为多字段唯一属性指定自定义 name

¥Specify a custom name for a multi-field unique attribute

model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)

@@unique(fields: [firstName, lastName, isAdmin], name: "admin_identifier")
}

要检索用户,请使用自定义字段名称 (admin_identifier):

¥To retrieve a user, use the custom field name (admin_identifier):

const user = await prisma.user.findUnique({
where: {
admin_identifier: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
},
});

@@index

定义数据库中的索引。

¥Defines an index in the database.

备注

¥Remarks

关系数据库

¥Relational databases

  • 对应的数据库构造:INDEX

    ¥Corresponding database construct: INDEX

  • 还有一些额外的索引配置选项尚无法通过 Prisma 模式提供。这些包括:

    ¥There are some additional index configuration options that cannot be provided via the Prisma schema yet. These include:

    • PostgreSQL 和 CockroachDB:

      ¥PostgreSQL and CockroachDB:

      • 将索引字段定义为表达式(例如 CREATE INDEX title ON public."Post"((lower(title)) text_ops);

        ¥Define index fields as expressions (e.g. CREATE INDEX title ON public."Post"((lower(title)) text_ops);)

      • 使用 WHERE 定义部分索引

        ¥Define partial indexes with WHERE

      • CONCURRENTLY 同时创建索引

        ¥Create indexes concurrently with CONCURRENTLY

info

虽然你无法在 Prisma 架构中配置这些选项,但你仍然可以直接在数据库级别配置它们。

¥While you cannot configure these option in your Prisma schema, you can still configure them on the database-level directly.

MongoDB

参数

¥Arguments

名称必需的类型描述
fields是的FieldReference[]字段名称列表 - 例如,["firstname", "lastname"]
nameStringPrisma 客户端将为涵盖所有字段的参数公开的名称,例如 fullNamefullName: { firstName: "First", lastName: "Last"}
mapmap底层数据库中索引的名称(如果你不指定名称,Prisma 会生成一个遵循标识符长度限制的索引名称。Prisma 使用以下命名约定:tablename.field1_field2_field3_unique
lengthnumber允许你指定要索引的值的子部分的最大长度。仅限

MySQL。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
sortString允许你指定索引或约束条目在数据库中的存储顺序。可用选项为 ascdesc

在 3.5.0 及更高版本中预览,在 4.0.0 及更高版本中全面可用。
clusteredBoolean定义索引是聚集索引还是非聚集索引。默认仅适用于 false.

SQL Server。在 3.5.0 及更高版本中提供预览版,并在 4.0.0 及更高版本中提供正式版本。
typeidentifier允许你指定索引访问方法。仅默认为 BTree.

PostgreSQL 和 CockroachDB。在 3.6.0 及更高版本中预览使用 Hash 索引访问方法,并在 3.14.0 中添加 GistGinSpGistBrin 方法。4.0.0 及更高版本中普遍可用。
opsidentifierfunction允许你为某些索引类型定义索引运算符。

仅限 PostgreSQL。在 3.14.0 及更高版本中提供预览版,在 4.0.0 及更高版本中提供正式版本。

@@index 属性上的 fields 参数的名称可以省略:

¥The name of the fields argument on the @@index attribute can be omitted:

@@index(fields: [title, author])
@@index([title, author])

lengthsort 参数被添加到相关字段名称中:

¥The length and sort arguments are added to the relevant field names:

@@index(fields: [title(length:10), author])
@@index([title(sort: Asc), author(sort: Desc)])

签名

¥Signature

@@index(_ fields: FieldReference[], map: String?)

注意:在 3.0.0 版本之前,签名为:

¥Note: Until version 3.0.0, the signature was:

@@index(_ fields: FieldReference[], name: String?)

旧的 name 参数仍将被接受以避免重大更改。

¥The old name argument will still be accepted to avoid a breaking change.

示例

¥Examples

假设要为 Post 模型的 title 字段添加索引

¥Assume you want to add an index for the title field of the Post model

定义单列索引(仅限关系数据库)

¥Define a single-column index (Relational databases only)

model Post {
id Int @id @default(autoincrement())
title String
content String?

@@index([title])
}
定义多列索引(仅限关系数据库)

¥Define a multi-column index (Relational databases only)

model Post {
id Int @id @default(autoincrement())
title String
content String?

@@index([title, content])
}
使用名称定义索引(仅限关系数据库)

¥Define an index with a name (Relational databases only)

model Post {
id Int @id @default(autoincrement())
title String
content String?

@@index(fields: [title, content], name: "main_index")
}
在复合类型字段上定义索引(仅限关系数据库)

¥Define an index on a composite type field (Relational databases only)

type Address {
street String
number Int
}

model User {
id Int @id
email String
address Address

@@index([address.number])
}

@relation

定义有关关系的元信息。了解更多

¥Defines meta information about the relation. Learn more.

备注

¥Remarks

关系数据库

¥Relational databases

  • 对应的数据库构造:FOREIGN KEY/REFERENCES

    ¥Corresponding database constructs: FOREIGN KEY / REFERENCES

MongoDB
  • 如果你的模型的主键在基础数据库中是 ObjectId 类型,则主键和外键都必须具有 @db.ObjectId 属性

    ¥If your model's primary key is of type ObjectId in the underlying database, both the primary key and the foreign key must have the @db.ObjectId attribute

参数

¥Arguments

名称类型必需的描述示例
nameString有时(例如为了消除关系的歧义)定义关系的名称。在 m-n-关系中,它还确定基础关系表的名称。"CategoryOnPost""MyRelation"
fieldsFieldReference[]annotated 关系字段上当前型号 fields 列表["authorId"]["authorFirstName, authorLastName"]
referencesFieldReference[]annotated 关系字段上关系另一端模型的 fields 列表["id"]["firstName, lastName"]
mapString为数据库中的外键定义 自定义名称["id"]["firstName, lastName"]
onUpdate枚举。有关值,请参阅 参考动作的类型定义当更新引用模型中的引用条目时要执行的 参考行动CascadeNoAction
onDelete枚举。有关值,请参阅 参考动作的类型定义删除引用模型中的引用条目时要执行的 参考行动CascadeNoAction

@relation 属性上的 name 参数的名称可以省略(references 是必需的):

¥The name of the name argument on the @relation attribute can be omitted (references is required):

@relation(name: "UserOnPost", references: [id])
@relation("UserOnPost", references: [id])

// or

@relation(name: "UserOnPost")
@relation("UserOnPost")

签名

¥Signature

@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?, map: String?)

使用 SQLite,签名更改为:

¥With SQLite, the signature changes to:

@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?)

注意:在 3.0.0 版本之前,签名为:

¥Note: Until version 3.0.0, the signature was:

@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?)

示例

¥Examples

看:@relation 属性

¥See: The @relation attribute.

@map

将 Prisma 架构中的字段名称或枚举值映射到数据库中具有不同名称的列或文档字段。如果你不使用 @map,Prisma 字段名称与列名称或文档字段名称完全匹配。

¥Maps a field name or enum value from the Prisma schema to a column or document field with a different name in the database. If you do not use @map, the Prisma field name matches the column name or document field name exactly.

请参阅 使用自定义模型和字段名称,了解 @map@@map 如何更改生成的 Prisma Client。

¥See Using custom model and field names to see how @map and @@map changes the generated Prisma Client.

备注

¥Remarks

一般的

¥General

MongoDB

你的 @id 字段必须包含 @map("_id")。例如:

¥Your @id field must include @map("_id"). For example:

model User {
id String @default(auto()) @map("_id") @db.ObjectId
}

参数

¥Arguments

名称类型必需的描述示例
nameString是的数据库列(关系数据库)或文档字段(MongoDB)名称。"comments""someFieldName"

@map 属性上的 name 参数的名称可以省略:

¥The name of the name argument on the @map attribute can be omitted:

@map(name: "is_admin")
@map("users")

签名

¥Signature

@map(_ name: String)

示例

¥Examples

firstName 字段映射到名为 first_name 的列

¥Map the firstName field to a column called first_name

model User {
id Int @id @default(autoincrement())
firstName String @map("first_name")
}

生成的客户端:

¥The generated client:

await prisma.user.create({
data: {
firstName: "Yewande", // first_name --> firstName
},
});
将名为 ADMIN 的枚举映射到名为 admin 的数据库枚举

¥Map an enum named ADMIN to a database enum named admin

enum Role {
ADMIN @map("admin")
CUSTOMER
}

@@map

将 Prisma 架构模型名称映射到具有不同名称的表(关系数据库)或集合 (MongoDB),或将枚举名称映射到数据库中不同的底层枚举。如果不使用 @@map,则模型名称与表(关系数据库)或集合(MongoDB)名称完全匹配。

¥Maps the Prisma schema model name to a table (relational databases) or collection (MongoDB) with a different name, or an enum name to a different underlying enum in the database. If you do not use @@map, the model name matches the table (relational databases) or collection (MongoDB) name exactly.

请参阅 使用自定义模型和字段名称,了解 @map@@map 如何更改生成的 Prisma Client。

¥See Using custom model and field names to see how @map and @@map changes the generated Prisma Client.

参数

¥Arguments

名称类型必需的描述示例
nameString是的数据库表(关系数据库)或集合(MongoDB)名称。"comments""someTableOrCollectionName"

@@map 属性上的 name 参数的名称可以省略

¥The name of the name argument on the @@map attribute can be omitted

@@map(name: "users")
@@map("users")

签名

¥Signature

@@map(_ name: String)

示例

¥Examples

User 模型映射到名为 users 的数据库表/集合

¥Map the User model to a database table/collection named users

model User {
id Int @id @default(autoincrement())
name String

@@map("users")
}

生成的客户端:

¥The generated client:

await prisma.user.create({
// users --> user
data: {
name: "Yewande",
},
});
Role 枚举映射到数据库中名为 _Role 的原生枚举,将其值映射到数据库中的小写值

¥Map the Role enum to a native enum in the database named _Role its values to lowercase values in the database

enum Role {
ADMIN @map("admin")
CUSTOMER @map("customer")

@@map("_Role")
}

@updatedAt

自动存储记录上次更新的时间。如果你自己不提供时间,Prisma 客户端将自动设置具有此属性的字段的值。

¥Automatically stores the time when a record was last updated. If you do not supply a time yourself, Prisma Client will automatically set the value for fields with this attribute.

备注

¥Remarks

  • 兼容 DateTime 字段

    ¥Compatible with DateTime fields

  • 在 Prisma ORM 级别实现

    ¥Implemented at Prisma ORM level

警告

4.4.0 之前的版本中,如果你同时使用 now(),并且数据库和应用位于不同的时区,则时间可能与 @updatedAt 的值不同。发生这种情况的原因是 @updatedAt 在 Prisma ORM 级别运行,而 now() 在数据库级别运行。

¥In versions before 4.4.0, if you're also using now(), the time might differ from the @updatedAt values if your database and app have different time zones. This happens because @updatedAt operates at the Prisma ORM level, while now() operates at the database level.

注意

如果你传递一个空的更新子句,@updatedAt 值将保持不变。例如:

¥If you pass an empty update clause, the @updatedAt value will remain unchanged. For example:

await prisma.user.update({
where: {
id: 1,
},
data: {}, //<- Empty update clause
});

参数

¥Arguments

不适用

¥N/A

签名

¥Signature

@updatedAt

示例

¥Examples

model Post {
id String @id
updatedAt DateTime @updatedAt
}

@ignore

@ignore 添加到你想要从 Prisma Client 中排除的字段(例如,你不希望 Prisma Client 用户更新的字段)。忽略的字段将从生成的 Prisma 客户端中排除。当对没有 @default 的必填字段执行此操作时,模型的 create 方法将被禁用(因为数据库无法创建没有该数据的条目)。

¥Add @ignore to a field that you want to exclude from Prisma Client (for example, a field that you do not want Prisma Client users to update). Ignored fields are excluded from the generated Prisma Client. The model's create method is disabled when doing this for required fields with no @default (because the database cannot create an entry without that data).

备注

¥Remarks

  • 2.17.0 及更高版本中,当你内省时,Prisma ORM 会自动将 @ignore 添加到引用无效模型的字段中。

    ¥In 2.17.0 and later, Prisma ORM automatically adds @ignore to fields that refer to invalid models when you introspect.

示例

¥Examples

以下示例演示手动添加 @ignore 以从 Prisma 客户端中排除 email 字段:

¥The following example demonstrates manually adding @ignore to exclude the email field from Prisma Client:

schema.prisma
model User {
id Int @id
name String
email String @ignore // this field will be excluded
}

@@ignore

@@ignore 添加到你想要从 Prisma 客户端中排除的模型(例如,你不希望 Prisma 用户更新的模型)。忽略的模型将从生成的 Prisma 客户端中排除。

¥Add @@ignore to a model that you want to exclude from Prisma Client (for example, a model that you do not want Prisma users to update). Ignored models are excluded from the generated Prisma Client.

备注

¥Remarks

  • 2.17.0 及更高版本中,Prisma ORM 将 @@ignore 添加到无效模型中。(它还将 @ignore 添加到指向此类模型的关系中)

    ¥In 2.17.0 and later, Prisma ORM adds @@ignore to an invalid model. (It also adds @ignore to relations pointing to such a model)

示例

¥Examples

在以下示例中,Post 模型无效,因为它没有唯一标识符。使用 @@ignore 将其从生成的 Prisma 客户端 API 中排除:

¥In the following example, the Post model is invalid because it does not have a unique identifier. Use @@ignore to exclude it from the generated Prisma Client API:

schema.prisma
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model Post {
id Int @default(autoincrement()) // no unique identifier
author User @relation(fields: [authorId], references: [id])
authorId Int

@@ignore
}

在以下示例中,Post 模型无效,因为它没有唯一标识符,User 上的 posts 关系字段无效,因为它引用了无效的 Post 模型。在 Post 模型上使用 @@ignore,在 User 中的 posts 关系字段上使用 @ignore,以从生成的 Prisma 客户端 API 中排除模型和关系字段:

¥In the following example, the Post model is invalid because it does not have a unique identifier, and the posts relation field on User is invalid because it refers to the invalid Post model. Use @@ignore on the Post model and @ignore on the posts relation field in User to exclude both the model and the relation field from the generated Prisma Client API:

schema.prisma
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.
model Post {
id Int @default(autoincrement()) // no unique identifier
author User @relation(fields: [authorId], references: [id])
authorId Int

@@ignore
}

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

@@schema

warning

要使用此属性,你必须启用 multiSchema 预览功能。目前,PostgreSQL、CockroachDB 和 SQL Server 连接器提供多数据库模式支持。

¥To use this attribute, you must have the multiSchema preview feature enabled. Multiple database schema support is currently available with the PostgreSQL, CockroachDB, and SQL Server connectors.

@@schema 添加到模型以指定数据库中的哪个架构应包含与该模型关联的表。

¥Add @@schema to a model to specify which schema in your database should contain the table associated with that model.

参数

¥Arguments

名称类型必需的描述示例
nameString是的数据库模式的名称。"base""auth"

@@schema 属性上的 name 参数的名称可以省略

¥The name of the name argument on the @@schema attribute can be omitted

@@schema(name: "auth")
@@schema("auth")

签名

¥Signature

@@schema(_ name: String)

示例

¥Examples

User 模型映射到名为 auth 的数据库架构

¥Map the User model to a database schema named auth

generator client {
provider = "prisma-client-js"
previewFeatures = ["multiSchema"]
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
schemas = ["auth"]
}

model User {
id Int @id @default(autoincrement())
name String

@@schema("auth")
}
info

有关使用 multiSchema 功能的更多信息,请参阅 本指南

¥For more information about using the multiSchema feature, refer to this guide.

@shardKey

注意

此功能需要你的 generator 上启用 shardKeys 预览功能标志:

¥This features requires the shardKeys Preview feature flag on your generator:

generator client {
provider = "prisma-client-js"
output = "../generated/prisma"
previewFeatures = ["shardKeys"]
}

@shardKey 属性仅与 PlanetScale 数据库兼容。它允许你在模型的某个字段上定义 分片键

¥The @shardKey attribute is only compatible with PlanetScale databases. It enables you define a shard key on a field of your model:

model User {
id String @default(uuid())
region String @shardKey
}

@@shardKey

注意

此功能需要你的 generator 上启用 shardKeys 预览功能标志:

¥This features requires the shardKeys Preview feature flag on your generator:

generator client {
provider = "prisma-client-js"
output = "../generated/prisma"
previewFeatures = ["shardKeys"]
}

@shardKey 属性仅与 PlanetScale 数据库兼容。它允许你在模型的多个字段上定义 分片键

¥The @shardKey attribute is only compatible with PlanetScale databases. It enables you define a shard key on multiple fields of your model:

model User {
id String @default(uuid())
country String
customerId String
@@shardKey([country, customerId])
}

属性函数

¥Attribute functions

auto()

warning
This function is available on MongoDB only.

表示由数据库自动生成的默认值。

¥Represents default values that are automatically generated by the database.

备注

¥Remarks

MongoDB

用于为 @id 字段生成 ObjectId

¥Used to generate an ObjectId for @id fields:

id  String  @map("_id") @db.ObjectId @default(auto())
关系数据库

¥Relational databases

auto() 函数在关系数据库上不可用。

¥The auto() function is not available on relational databases.

示例

¥Example

生成 ObjectId(仅限 MongoDB)

¥Generate ObjectId (MongoDB only)

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String?
}

autoincrement()

warning

MongoDB 不支持
MongoDB 连接器 不支持 autoincrement() 功能。

¥Not supported by MongoDB
The MongoDB connector does not support the autoincrement() function.

在底层数据库中创建一个整数序列,并根据序列将递增的值分配给创建的记录的 ID 值。

¥Create a sequence of integers in the underlying database and assign the incremented values to the ID values of the created records based on the sequence.

备注

¥Remarks

  • 与大多数数据库上的 Int 兼容(CockroachDB 上的 BigInt

    ¥Compatible with Int on most databases (BigInt on CockroachDB)

  • 在数据库级别实现,这意味着它体现在数据库模式中,并且可以通过内省来识别。数据库实现:

    ¥Implemented on the database-level, meaning that it manifests in the database schema and can be recognized through introspection. Database implementations:

    数据库执行
    PostgreSQLSERIAL
    MySQLAUTO_INCREMENT 属性
    SQLiteAUTOINCREMENT 关键字
    CockroachDBSERIAL

示例

¥Examples

生成自动递增整数作为 ID(仅限关系数据库)

¥Generate autoincrementing integers as IDs (Relational databases only)

model User {
id Int @id @default(autoincrement())
name String
}

sequence()

info

仅 CockroachDB
支持 序列功能仅 CockroachDB 连接器 支持。

¥Only supported by CockroachDB
The sequence function is only supported by CockroachDB connector.

在底层数据库中创建一个整数序列,并根据该序列将递增的值分配给创建的记录的值。

¥Create a sequence of integers in the underlying database and assign the incremented values to the values of the created records based on the sequence.

可选参数

¥Optional arguments

争论示例
virtual@default(sequence(virtual))
虚拟序列是不生成单调递增值的序列,而是生成类似于内置函数 unique_rowid() 生成的值。
cache@default(sequence(cache: 20))
要在内存中缓存以便在会话中重用的序列值的数量。缓存大小为 1 意味着没有缓存,小于 1 的缓存大小无效。
increment@default(sequence(increment: 4))
序列递增的新值。负数创建降序序列。正数创建升序序列。
minValue@default(sequence(minValue: 10))
序列的新最小值。
maxValue@default(sequence(maxValue: 3030303))
序列的新最大值。
start@default(sequence(start: 2))
序列开始时的值(如果序列已重新启动或序列到达 maxValue)。

示例

¥Examples

生成排序整数作为 ID

¥Generate sequencing integers as IDs

model User {
id Int @id @default(sequence(maxValue: 4294967295))
name String
}

cuid()

根据 cuid 规范生成全局唯一标识符。

¥Generate a globally unique identifier based on the cuid spec.

如果你想使用 cuid2 值,你可以将 2 作为参数传递给 cuid 函数:cuid(2)

¥If you'd like to use cuid2 values, you can pass 2 as an argument to the cuid function: cuid(2).

备注

¥Remarks

  • String 兼容。

    ¥Compatible with String.

  • 由 Prisma ORM 实现,因此在底层数据库模式中不是 "visible"。当通过 手动更改 Prisma 架构生成 Prisma 客户端 使用 introspection 时,你仍然可以使用 cuid(),在这种情况下,这些值将由 Prisma 的 查询引擎 生成。

    ¥Implemented by Prisma ORM and therefore not "visible" in the underlying database schema. You can still use cuid() when using introspection by manually changing your Prisma schema and generating Prisma Client, in that case the values will be generated by Prisma's query engine.

  • 由于每个 cuid 创建者未定义 cuid() 输出的长度,因此安全字段大小为 30 个字符,以便为非常大的值提供足够的字符。如果你将字段大小设置为小于 30,然后 cuid() 生成更大的值,你可能会看到 Prisma 客户端错误,例如 Error: The provided value for the column is too long for the column's type.

    ¥Since the length of cuid() output is undefined per the cuid creator, a safe field size is 30 characters, in order to allow for enough characters for very large values. If you set the field size as less than 30, and then a larger value is generated by cuid(), you might see Prisma Client errors such as Error: The provided value for the column is too long for the column's type.

  • 对于 MongoDB:cuid() 不会生成有效的 ObjectId。如果你想在底层数据库中使用 ObjectId,则可以使用 @db.ObjectId 语法。但是,如果你的 _id 字段不是 ObjectId 类型,你仍然可以使用 cuid()

    ¥For MongoDB: cuid() does not generate a valid ObjectId. You can use @db.ObjectId syntax if you want to use ObjectId in the underlying database. However, you can still use cuid() if your _id field is not of type ObjectId.

示例

¥Examples

生成 cuid() 值作为 ID

¥Generate cuid() values as IDs

model User {
id String @id @default(cuid())
name String
}
根据 cuid2 规范生成 cuid(2) 值作为 ID

¥Generate cuid(2) values as IDs based on the cuid2 spec

model User {
id String @id @default(cuid(2))
name String
}

uuid()

根据 UUID 规范生成全局唯一标识符。Prisma ORM 支持版本 4(默认)和 7。

¥Generate a globally unique identifier based on the UUID spec. Prisma ORM supports versions 4 (default) and 7.

备注

¥Remarks

示例

¥Examples

使用 UUID v4 生成 uuid() 值作为 ID

¥Generate uuid() values as IDs using UUID v4

model User {
id String @id @default(uuid())
name String
}
使用 UUID v7 生成 uuid(7) 值作为 ID

¥Generate uuid(7) values as IDs using UUID v7

model User {
id String @id @default(uuid(7))
name String
}

ulid()

根据 ULID 规范生成一个通用唯一的可按字典顺序排序的标识符。

¥Generate a universally unique lexicographically sortable identifier based on the ULID spec.

备注

¥Remarks

  • ulid() 将生成 128 位随机标识符,表示为 26 个字符长的字母数字字符串,例如:01ARZ3NDEKTSV4RRFFQ69G5FAV

    ¥ulid() will produce 128-bit random identifier represented as a 26-character long alphanumeric string, e.g.: 01ARZ3NDEKTSV4RRFFQ69G5FAV

示例

¥Examples

生成 ulid() 值作为 ID

¥Generate ulid() values as IDs

model User {
id String @id @default(ulid())
name String
}

nanoid()

基于 Nano ID 规范生成的值。nanoid() 接受 2 到 255 之间的整数值,用于指定生成 ID 值的长度,例如 nanoid(16) 将生成 16 个字符的 ID。如果你没有为 nanoid() 函数提供值,则默认值为 21。

¥Generated values based on the Nano ID spec. nanoid() accepts an integer value between 2 and 255 that specifies the length of the generate ID value, e.g. nanoid(16) will generated ID with 16 characters. If you don't provide a value to the nanoid() function, the default value is 21.

信息

Nano ID 与 UUID v4(基于随机)相当。它在 ID 中具有类似数量的随机位(Nano ID 中为 126,UUID 中为 122),因此具有类似的碰撞概率:

¥Nano ID is quite comparable to UUID v4 (random-based). It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability:

为了有十亿分之一的重复几率,必须生成 103 万亿个版本 4 ID。

¥For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.

Nano ID 和 UUID v4 之间有两个主要区别:

¥There are two main differences between Nano ID and UUID v4:

  • Nano ID 使用更大的字母表,因此类似数量的随机位仅包含在 21 个符号中,而不是 36 个。

    ¥Nano ID uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.

  • Nano ID 代码比 uuid/v4 包小 4 倍:130 字节而不是 423 字节。

    ¥Nano ID code is 4 times smaller than uuid/v4 package: 130 bytes instead of 423.

备注

¥Remarks

  • String 兼容。

    ¥Compatible with String.

  • 由 Prisma ORM 实现,因此在底层数据库模式中不是 "visible"。当通过 手动更改 Prisma 架构生成 Prisma 客户端 使用 introspection 时,你仍然可以使用 uuid(),在这种情况下,这些值将由 Prisma ORM 的 查询引擎 生成。

    ¥Implemented by Prisma ORM and therefore not "visible" in the underlying database schema. You can still use uuid() when using introspection by manually changing your Prisma schema and generating Prisma Client, in that case the values will be generated by Prisma ORM's query engine.

  • 对于 MongoDB:nanoid() 不会生成有效的 ObjectId。如果你想在底层数据库中使用 ObjectId,则可以使用 @db.ObjectId 语法。但是,如果你的 _id 字段不是 ObjectId 类型,你仍然可以使用 nanoid()

    ¥For MongoDB: nanoid() does not generate a valid ObjectId. You can use @db.ObjectId syntax if you want to use ObjectId in the underlying database. However, you can still use nanoid() if your _id field is not of type ObjectId.

示例

¥Examples

生成 21 个字符的 nanoid() 值作为 ID

¥Generate nanoid() values with 21 characters as IDs

model User {
id String @id @default(nanoid())
name String
}
生成 16 个字符的 nanoid() 值作为 ID

¥Generate nanoid() values with 16 characters as IDs

model User {
id String @id @default(nanoid(16))
name String
}

now()

设置创建记录时的时间戳。

¥Set a timestamp of the time when a record is created.

备注

¥Remarks

一般的

¥General

警告

4.4.0 之前的版本中,如果你同时使用 @updatedAt,并且数据库和应用位于不同的时区,则时间可能与 now() 的值不同。发生这种情况的原因是 @updatedAt 在 Prisma ORM 级别运行,而 now() 在数据库级别运行。

¥In versions before 4.4.0, if you're also using @updatedAt, the time might differ from the now() values if your database and app have different time zones. This happens because @updatedAt operates at the Prisma ORM level, while now() operates at the database level.

关系数据库

¥Relational databases

  • 在数据库级别实现,这意味着它体现在数据库模式中,并且可以通过内省来识别。数据库实现:

    ¥Implemented on the database-level, meaning that it manifests in the database schema and can be recognized through introspection. Database implementations:

    数据库执行
    PostgreSQLCURRENT_TIMESTAMP 和别名(如 now()
    MySQLCURRENT_TIMESTAMP 和别名(如 now()
    SQLiteCURRENT_TIMESTAMP 和别名(如 date('now')
    CockroachDBCURRENT_TIMESTAMP 和别名(如 now()
MongoDB
  • 在 Prisma ORM 级别实现

    ¥Implemented at Prisma ORM level

示例

¥Examples

创建记录时设置当前时间戳值

¥Set current timestamp value when a record is created

model User {
id String @id
createdAt DateTime @default(now())
}

dbgenerated(...)

表示无法在 Prisma 模式中表达的默认值(例如 random())。

¥Represents default values that cannot be expressed in the Prisma schema (such as random()).

备注

¥Remarks

关系数据库

¥Relational databases

  • 与任何标量类型兼容

    ¥Compatible with any scalar type

  • 2.21.0 及更高版本中,dbgenerated("") 不能为空字符串

    ¥Can not be an empty string dbgenerated("") in 2.21.0 and later

  • 接受 2.17.0 及更高版本中的 String 值,这允许你:

    ¥Accepts a String value in 2.17.0 and later, which allows you to:

  • dbgenerated(...) 中的字符串值可能与数据库返回的默认值不匹配,因为诸如字符串之类的值可能会被显式转换(例如 'hello'::STRING)。当存在不匹配时,Prisma Migrate 指示仍需要迁移。你可以使用 prisma db pull 推断正确的值来解决差异。(相关问题)

    ¥String values in dbgenerated(...) might not match what the DB returns as the default value, because values such as strings may be explicitly cast (e.g. 'hello'::STRING). When a mismatch is present, Prisma Migrate indicates a migration is still needed. You can use prisma db pull to infer the correct value to resolve the discrepancy. (Related issue)

示例

¥Examples

设置 Unsupported 类型的默认值

¥Set default value for Unsupported type

circle     Unsupported("circle")?   @default(dbgenerated("'<(10,4),11>'::circle"))
覆盖支持类型的默认值行为

¥Override default value behavior for supported types

你还可以使用 dbgenerated(...) 设置支持类型的默认值。例如,在 PostgreSQL 中,你可以在数据库级别生成 UUID,而不是依赖 Prisma ORM 的 uuid()

¥You can also use dbgenerated(...) to set the default value for supported types. For example, in PostgreSQL you can generate UUIDs at the database level rather than rely on Prisma ORM's uuid():

model User {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
id String @id @default(uuid()) @db.Uuid
test String?
}
info

注意:gen_random_uuid() 是 PostgreSQL 函数。要在 PostgreSQL 版本 12.13 及更早版本中使用它,你必须启用 pgcrypto 扩展。

在 Prisma ORM 版本 4.5.0 及更高版本中,你可以使用 postgresqlExtensions 预览功能 在 Prisma 模式中声明 pgcrypto 扩展。

¥Note: gen_random_uuid() is a PostgreSQL function. To use it in PostgreSQL versions 12.13 and earlier, you must enable the pgcrypto extension.

In Prisma ORM versions 4.5.0 and later, you can declare the pgcrypto extension in your Prisma schema with the postgresqlExtensions preview feature.

属性参数类型

¥Attribute argument types

FieldReference[]

field 名称数组:[id][firstName, lastName]

¥An array of field names: [id], [firstName, lastName]

String

双引号中的可变长度文本:"""Hello World""Alice"

¥A variable length text in double quotes: "", "Hello World", "Alice"

Expression

可以通过 Prisma ORM 计算的表达式:42.0""Bobnow()cuid()

¥An expression that can be evaluated by Prisma ORM: 42.0, "", Bob, now(), cuid()

enum

warning

不支持 Microsoft SQL Server
微软 SQL Server 连接器 不支持 enum 类型。

¥Not supported Microsoft SQL Server
The Microsoft SQL Server connector does not support the enum type.

定义 enum

¥Defines an enum .

备注

¥Remarks

  • PostgreSQLMySQL 原生支持枚举

    ¥Enums are natively supported by PostgreSQL and MySQL

  • 枚举在 SQLite 和 MongoDB 中的 Prisma ORM 级别实现和执行

    ¥Enums are implemented and enforced at Prisma ORM level in SQLite and MongoDB

命名约定

¥Naming conventions

  • 枚举名称必须以字母开头(通常以 PascalCase 拼写)

    ¥Enum names must start with a letter (they are typically spelled in PascalCase)

  • 枚举必须使用单数形式(例如 Role 而不是 rolerolesRoles)。

    ¥Enums must use the singular form (e.g. Role instead of role, roles or Roles).

  • 必须遵守以下正则表达式:[A-Za-z][A-Za-z0-9_]*

    ¥Must adhere to the following regular expression: [A-Za-z][A-Za-z0-9_]*

示例

¥Examples

指定具有两个可能值的 enum

¥Specify an enum with two possible values

enum Role {
USER
ADMIN
}

model User {
id Int @id @default(autoincrement())
role Role
}

指定具有两个可能值的 enum 并设置默认值

¥Specify an enum with two possible values and set a default value

enum Role {
USER
ADMIN
}

model User {
id Int @id @default(autoincrement())
role Role @default(USER)
}

type

warning

复合类型仅适用于 MongoDB。

¥Composite types are available for MongoDB only.

info

复合类型在版本 3.12.0 及更高版本中可用,如果你启用 mongodb 预览功能标志,则在版本 3.10.0 及更高版本中可用。

¥Composite types are available in versions 3.12.0 and later, and in versions 3.10.0 and later if you enable the mongodb Preview feature flag.

定义 复合型

¥Defines a composite type .

命名约定

¥Naming conventions

类型名称必须:

¥Type names must:

  • 以字母开头(通常拼写为 PascalCase

    ¥start with a letter (they are typically spelled in PascalCase)

  • 遵守以下正则表达式:[A-Za-z][A-Za-z0-9_]*

    ¥adhere to the following regular expression: [A-Za-z][A-Za-z0-9_]*

示例

¥Examples

使用 Photo 复合类型列表定义 Product 模型

¥Define a Product model with a list of Photo composite types

model Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
photos Photo[]
}

type Photo {
height Int
width Int
url String
}