跳到主要內容

Prisma Schema 參考

datasource

在 Prisma Schema 中定義一個資料來源

欄位

一個 datasource 塊接受以下欄位

名稱必需型別描述
provider字串 (postgresql, mysql, sqlite, sqlserver, mongodb, cockroachdb)描述要使用的資料來源聯結器。
url字串 (URL)連線 URL,包括認證資訊。大多數聯結器使用資料庫提供的語法
shadowDatabaseUrl字串 (URL)Prisma Migrate 使用的影子資料庫的連線 URL。允許你使用雲託管資料庫作為影子資料庫。
directUrl字串 (URL)資料庫的直接連線 URL。

如果你在 url 引數中使用連線池 URL(例如,如果你使用 Prisma Accelerate 或 pgBouncer),則需要直接連線到資料庫的 Prisma CLI 命令會使用 directUrl 引數中的 URL。

Prisma Studio 從 5.1.0 版本開始支援 directUrl 屬性。

使用 Prisma Postgres 資料庫時不需要 directUrl 屬性。
relationMode字串 (foreignKeys, prisma)設定參照完整性是由資料庫中的外部索引鍵強制執行,還是在 Prisma Client 中模擬執行。

在 3.1.1 及更高版本中為預覽功能。在 4.5.0 及更高版本中,該欄位名為 relationMode,之前名為 referentialIntegrity
extensions字串列表 (PostgreSQL 副檔名稱)允許你在 Schema 中表示 PostgreSQL 擴充套件。在 Prisma ORM 4.5.0 及更高版本中,此功能僅在 PostgreSQL 上作為預覽版提供。

以下提供者可用

備註

  • 一個 Schema 中只能有一個 datasource 塊。
  • datasource db 是一種約定——但你可以為你的資料來源指定任何名稱——例如,datasource mysqldatasource data

示例

指定 PostgreSQL 資料來源

在此示例中,目標資料庫可使用以下憑據訪問

  • 使用者: johndoe
  • 密碼: mypassword
  • 主機: localhost
  • 埠: 5432
  • 資料庫名稱: mydb
  • Schema 名稱: public
datasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public"
}

瞭解更多關於 PostgreSQL 連線字串的資訊,請點選此處

透過環境變數指定 PostgreSQL 資料來源

在此示例中,目標資料庫可使用以下憑據訪問

  • 使用者: johndoe
  • 密碼: mypassword
  • 主機: localhost
  • 埠: 5432
  • 資料庫名稱: mydb
  • Schema 名稱: public
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

執行需要資料庫連線 URL 的 Prisma CLI 命令(例如 prisma generate)時,你需要確保 DATABASE_URL 環境變數已設定。

一種方法是建立一個包含以下內容的.env檔案。請注意,該檔案必須與你的 schema.prisma 檔案位於同一目錄中,Prisma CLI 才能自動檢測到它。

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

指定 MySQL 資料來源

在此示例中,目標資料庫可使用以下憑據訪問

  • 使用者: johndoe
  • 密碼: mypassword
  • 主機: localhost
  • 埠: 3306
  • 資料庫名稱: mydb
datasource db {
provider = "mysql"
url = "mysql://johndoe:mypassword@localhost:3306/mydb"
}

瞭解更多關於 MySQL 連線字串的資訊,請點選此處

指定 MongoDB 資料來源

  • 使用者: root
  • 密碼: password
  • 主機: cluster1.test1.mongodb.net
  • 埠: 不適用
  • 資料庫名稱: testing
datasource db {
provider = "mongodb"
url = "mongodb+srv://root:password@cluster1.test1.mongodb.net/testing?retryWrites=true&w=majority"
}

瞭解更多關於 MongoDB 連線字串的資訊,請點選此處

指定 SQLite 資料來源

在此示例中,目標資料庫位於名為 dev.db 的檔案中

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

瞭解更多關於 SQLite 連線字串的資訊,請點選此處

指定 CockroachDB 資料來源

在此示例中,目標資料庫可使用以下憑據訪問

  • 使用者: johndoe
  • 密碼: mypassword
  • 主機: localhost
  • 埠: 26257
  • 資料庫名稱: mydb
  • Schema 名稱: public
datasource db {
provider = "cockroachdb"
url = "postgresql://johndoe:mypassword@localhost:26257/mydb?schema=public"
}

連線字串的格式與 PostgreSQL 相同。瞭解更多關於 PostgreSQL 連線字串的資訊,請點選此處

generator

在 Prisma Schema 中定義一個生成器

prisma-client-js 提供者的欄位

一個 generator 塊接受以下欄位

名稱必需型別描述
provider字串 (檔案路徑) 或 prisma-client-js描述要使用的生成器。這可以指向一個實現生成器的檔案,或者直接指定一個內建生成器。
output否*字串 (檔案路徑)確定生成客戶端的位置,瞭解更多預設值: node_modules/.prisma/client
previewFeatures列舉列表使用智慧感知檢視當前可用的預覽功能列表(在 Visual Studio Code 中按 Ctrl+Space)。預設值: 無
engineType列舉 (librarybinary)定義要下載和使用的查詢引擎型別。預設值: library
binaryTargets列舉列表(見下文)指定 Prisma Client 執行的作業系統,以確保查詢引擎的相容性。預設值: native
moduleFormat列舉 (cjsesm)定義生成的 Prisma Client 的模組格式。此欄位僅適用於 prisma-client 生成器。
重要

我們建議定義一個自定義輸出路徑,將該路徑新增到 .gitignore,然後確保透過自定義構建指令碼或 postinstall hook 執行 prisma generate

prisma-client 提供者的欄位 (搶先體驗)

一個 generator 塊接受以下欄位

名稱必需型別描述
provider字串 (檔案路徑) 或 prisma-client描述要使用的生成器。這可以指向一個實現生成器的檔案,或者直接指定一個內建生成器。
output字串 (檔案路徑)確定生成客戶端的位置,瞭解更多
previewFeatures列舉列表使用智慧感知檢視當前可用的預覽功能列表(在 Visual Studio Code 中按 Ctrl+Space)。預設值: 無
runtime列舉 (nodejs (別名 node), deno, bun, deno-deploy, workerd (別名 cloudflare), edge-light (別名 vercel), react-native)目標執行時環境。預設值: nodejs
moduleFormat列舉 (esmcjs)確定生成的程式碼是否支援 ESM(使用 import)或 CommonJS(使用 require(...))模組。我們總是推薦 esm,除非你有充分的理由使用 cjs預設值: 從環境中推斷。
generatedFileExtension列舉 (tsmtscts)生成的 TypeScript 檔案的副檔名。預設值: ts
importFileExtension列舉 (ts,mts,cts,js,mjs,cjs, 空 (用於裸匯入))匯入語句中使用的副檔名。預設值: 從環境中推斷。

binaryTargets 選項

下表列出了所有支援的作業系統,以及在binaryTargets中指定的平臺名稱。

除非另有說明,否則預設支援的 CPU 架構是 x86_64。

macOS
構建作業系統Prisma 引擎構建名稱
macOS Intel x86_64darwin
macOS ARM64darwin-arm64
Windows
構建作業系統Prisma 引擎構建名稱
Windowswindows
Linux (x86_64 架構上的 Alpine)
構建作業系統Prisma 引擎構建名稱OpenSSL
Alpine (3.17 及更新版本)linux-musl-openssl-3.0.x*3.0.x
Alpine (3.16 及更舊版本)linux-musl1.1.x

* 在 Prisma ORM 4.8.0 及更高版本中可用。

Linux (ARM64 架構上的 Alpine)
構建作業系統Prisma 引擎構建名稱OpenSSL
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 及更高版本中可用。

Linux (Debian), x86_64
構建作業系統Prisma 引擎構建名稱OpenSSL
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 引擎構建名稱OpenSSL
Ubuntu 14.04 (trusty)debian-openssl-1.0.x1.0.x
Ubuntu 16.04 (xenial)debian-openssl-1.0.x1.0.x
Ubuntu 18.04 (bionic)debian-openssl-1.1.x1.1.x
Ubuntu 19.04 (disco)debian-openssl-1.1.x1.1.x
Ubuntu 20.04 (focal)debian-openssl-1.1.x1.1.x
Ubuntu 21.04 (hirsute)debian-openssl-1.1.x1.1.x
Ubuntu 22.04 (jammy)debian-openssl-3.0.x3.0.x
Ubuntu 23.04 (lunar)debian-openssl-3.0.x3.0.x
Linux (CentOS), x86_64
構建作業系統Prisma 引擎構建名稱OpenSSL
CentOS 7rhel-openssl-1.0.x1.0.x
CentOS 8rhel-openssl-1.1.x1.1.x
Linux (Fedora), x86_64
構建作業系統Prisma 引擎構建名稱OpenSSL
Fedora 28rhel-openssl-1.1.x1.1.x
Fedora 29rhel-openssl-1.1.x1.1.x
Fedora 30rhel-openssl-1.1.x1.1.x
Fedora 36rhel-openssl-3.0.x3.0.x
Fedora 37rhel-openssl-3.0.x3.0.x
Fedora 38rhel-openssl-3.0.x3.0.x
Linux (Linux Mint), x86_64
構建作業系統Prisma 引擎構建名稱OpenSSL
Linux Mint 18debian-openssl-1.0.x1.0.x
Linux Mint 19debian-openssl-1.1.x1.1.x
Linux Mint 20debian-openssl-1.1.x1.1.x
Linux Mint 21debian-openssl-3.0.x3.0.x
Linux (Arch Linux), x86_64
構建作業系統Prisma 引擎構建名稱OpenSSL
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 外所有主要發行版)
構建作業系統Prisma 引擎構建名稱OpenSSL
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

示例

使用預設 outputpreviewFeaturesengineTypebinaryTargets 指定 prisma-client-js 生成器

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

請注意,上述 generator 定義與以下內容等效,因為它使用了 outputengineTypebinaryTargets(以及隱式 previewFeatures)的預設值。

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

為 Prisma Client 指定自定義 output 位置

此示例展示瞭如何定義生成資產的自定義 output 位置以覆蓋預設位置。

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

指定自定義 binaryTargets 以確保與作業系統的相容性

此示例展示瞭如何根據上表配置 Prisma Client 以在 Ubuntu 19.04 (disco) 上執行

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

指定指向自定義生成器實現的 provider

此示例展示瞭如何使用位於名為 my-generator 目錄中的自定義生成器。

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

model

定義一個 Prisma 模型

備註

  • 模型的每條記錄都必須是唯一可識別的。你必須為每個模型定義至少以下屬性之一

命名約定

  • 模型名稱必須遵循以下正則表示式:[A-Za-z][A-Za-z0-9_]*
  • 模型名稱必須以字母開頭,通常採用帕斯卡命名法(PascalCase)拼寫
  • 模型名稱應使用單數形式(例如,User 而不是 userusersUsers
  • Prisma ORM 有許多保留字供內部使用,因此不能用作模型名稱。你可以在此處此處找到這些保留字。

注意: 你可以使用@@map 屬性將模型(例如,User)對映到不符合模型命名約定的不同名稱的表(例如,users)。

欄位順序

  • 在 2.3.0 及更高版本中,內省會按照資料庫中相應列的順序列出模型欄位。關係欄位列在標量欄位之後。

示例

具有兩個標量欄位的名為 User 的模型

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

model 欄位

欄位是模型的屬性。

備註

命名約定

  • 必須以字母開頭
  • 通常採用駝峰命名法(camelCase)拼寫
  • 必須遵循以下正則表示式:[A-Za-z][A-Za-z0-9_]*

注意: 你可以使用@map 屬性欄位名稱對映到列,其名稱與欄位命名約定不符:例如 myField @map("my_field")

model 欄位標量型別

資料來源聯結器決定了每種 Prisma ORM 標量型別對映到哪種原生資料庫型別。類似地,生成器決定了這些型別中的每一種對映到目標程式語言中的哪種型別

Prisma 模型還具有定義模型之間關係的模型欄位型別

String

可變長度文字。

預設型別對映

聯結器預設對映
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

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

MongoDB

String

原生資料庫型別屬性備註
@db.String
@db.ObjectId如果底層 BSON 型別是 OBJECT_ID(ID 欄位,關係標量),則為必需。

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

請注意,PostgreSQL 支援的 xmlcitext 型別目前在 CockroachDB 中不受支援。

客戶端

Prisma Client JS
string

Boolean

真或假值。

預設型別對映

聯結器預設對映
PostgreSQLboolean
SQL Serverbit
MySQLTINYINT(1)
MongoDBBool
SQLiteINTEGER
CockroachDBBOOL

PostgreSQL

原生資料庫型別原生資料庫型別屬性備註
boolean@db.Boolean

MySQL

原生資料庫型別原生資料庫型別屬性備註
TINYINT(1)@db.TinyInt(1)如果最大長度大於 1(例如 TINYINT(2)預設值不是 10NULL,則 TINYINT 對映到 IntTINYINT(1) 對映到 Boolean
BIT(1)@db.Bit

MongoDB

Bool

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性備註
bit@db.Bit

SQLite

INTEGER

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
BOOL@db.Bool

客戶端

Prisma Client JS
boolean

Int

預設型別對映

聯結器預設對映
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

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性備註
int@db.Int
smallint@db.SmallInt
tinyint@db.TinyInt
bit@db.Bit

SQLite

INTEGER

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
INTEGER | INT | INT8@db.Int8請注意,這與 PostgreSQL 不同,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())

客戶端

Prisma Client JS
number

BigInt

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

預設型別對映

聯結器預設對映
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

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性備註
bigint@db.BigInt

SQLite

INTEGER

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
BIGINT | INT | INT8@db.Int8請注意,這與 PostgreSQL 不同,PostgreSQL 中 intint4 的別名
bigserial | serial8@db.Int8 @default(autoincrement())

客戶端

Client型別描述
Prisma Client JSBigInt請參閱使用 BigInt 的示例

Float

浮點數。

Float2.17.0 及更高版本中對映到 Double——有關此更改的更多資訊,請參閱發行說明影片:Prisma ORM 2.17.0 中 Float 預設對映的更改

預設型別對映

聯結器預設對映
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

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性
float@db.Float
money@db.Money
smallmoney@db.SmallMoney
real@db.Real

SQLite 聯結器

REAL

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
DOUBLE PRECISION | FLOAT8@db.Float8
REAL | FLOAT4 | FLOAT@db.Float4

客戶端

Prisma Client JS
number

Decimal

預設型別對映

聯結器預設對映
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(小數位數),小數點右側儲存的十進位制數字數量。

MySQL

原生資料庫型別原生資料庫型別屬性備註
DECIMAL | NUMERIC@db.Decimal(p, s)
  • p(精度),要儲存的最大十進位制數字總數。s(小數位數),小數點右側儲存的十進位制數字數量。

MongoDB

不支援.

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性備註
decimal | numeric@db.Decimal(p, s)
  • p(精度),要儲存的最大十進位制數字總數。s(小數位數),小數點右側儲存的十進位制數字數量。

SQLite

DECIMAL(在 2.17.0 中從 REAL 更改)

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
DECIMAL | DEC | NUMERIC@db.Decimal(p, s)
money尚未CockroachDB 尚未支援 PostgreSQL 的 money 型別
  • p(精度),要儲存的最大十進位制數字總數。s(小數位數),小數點右側儲存的十進位制數字數量。

客戶端

Client型別描述
Prisma Client JSDecimal請參閱使用 Decimal 的示例

DateTime

備註

  • Prisma Client 將所有 DateTime 作為原生的 Date 物件返回。
  • 目前,Prisma ORM 不支援 MySQL 中的零日期 (0000-00-00 00:00:00, 0000-00-00, 00:00:00)。
  • 目前存在一個錯誤,它不允許您將 DateTime 值作為字串傳入,否則會產生執行時錯誤。DateTime 值需要作為 Date 物件傳入(即 new Date('2024-12-04') 而不是 '2024-12-04')。

您可以在此部分找到更多資訊和示例:使用 DateTime

預設型別對映

聯結器預設對映
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 一起使用

yearField     Int    @db.Year

MongoDB

Timestamp

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性備註
date@db.Date
time@db.Time
datetime@db.DateTime
datetime2@db.DateTime2
smalldatetime@db.SmallDateTime
datetimeoffset@db.DateTimeOffset

SQLite

NUMERICSTRING。如果底層資料型別是 STRING,您必須使用以下格式之一

  • RFC 3339 (1996-12-19T16:39:57-08:00)
  • RFC 2822 (Tue, 1 Jul 2003 10:52:37 +0200)

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
TIMESTAMP(x)@db.Timestamp(x)
TIMESTAMPTZ(x)@db.Timestamptz(x)
DATE@db.Date
TIME(x)@db.Time(x)
TIMETZ(x)@db.Timetz(x)

客戶端

Prisma Client JS
Date

Json

一個 JSON 物件。

預設型別對映

聯結器預設對映
PostgreSQLjsonb
SQL Server不支援
MySQLJSON
MongoDB一個有效的 BSON 物件(寬鬆模式)
SQLiteJSONB
CockroachDBJSONB

PostgreSQL

原生資料庫型別原生資料庫型別屬性備註
json@db.Json
jsonb@db.JsonB

MySQL

原生資料庫型別原生資料庫型別屬性備註
JSON@db.Json

MongoDB

一個有效的 BSON 物件(寬鬆模式)

Microsoft SQL Server

Microsoft SQL Server 沒有專門的 JSON 資料型別。但是,有一些內建函式用於讀取和修改 JSON

SQLite

不支援

CockroachDB

原生資料庫型別原生資料庫型別屬性備註
JSON | JSONB@db.JsonB

客戶端

Prisma Client JS
object

Bytes

Bytes 在版本 2.17.0 及更高版本中可用。

預設型別對映

聯結器預設對映
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

Microsoft SQL Server

原生資料庫型別原生資料庫型別屬性備註
binary@db.Binary
varbinary@db.VarBinary
image@db.Image

SQLite

BLOB

CockroachDB

原生資料庫型別原生資料庫型別屬性
BYTES | BYTEA | BLOB@db.Bytes

客戶端

Client型別描述
Prisma Client JSUint8Array請參閱使用 Bytes 的示例
Prisma Client JS (v6 之前)Buffer請參閱使用 Bytes 的示例

Unsupported

警告

MongoDB 不支援
MongoDB 聯結器不支援 Unsupported 型別。

Unsupported 型別是在 2.17.0 及更高版本中引入的,允許您在 Prisma schema 中表示 Prisma Client 不支援的資料型別。Unsupported 型別的欄位可以在透過 prisma db pull 內省時建立,也可以手動編寫,並透過 Prisma Migrate 或 db push 在資料庫中建立。

備註

  • 生成的客戶端中不提供 Unsupported 型別的欄位。

  • 如果模型包含必需的 Unsupported 型別,則 Prisma Client 中不支援 prisma.model.create(..)prisma.model.update(...)prisma.model.upsert(...)

  • 當您內省包含不支援型別的資料庫時,Prisma ORM 將提供以下警告

    *** 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"

示例

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

model 欄位型別修飾符

[] 修飾符

使欄位成為列表。

備註

  • 不能是可選的(例如 Post[]?)。
關係型資料庫
  • 只有當您的資料庫原生支援標量列表(陣列)時,資料模型才支援它們。因此,目前僅在使用 PostgreSQL 或 CockroachDB 時支援標量列表(因為 MySQL 和 SQLite 不原生支援標量列表)。
MongoDB
  • 支援標量列表

示例

定義標量列表
model User {
id Int @id @default(autoincrement())
favoriteColors String[]
}
定義帶預設值的標量列表

在版本 4.0.0 及更高版本中可用。

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

? 修飾符

使欄位可選。

備註

  • 不能與列表欄位一起使用(例如 Posts[]

示例

可選 name 欄位
model User {
id Int @id @default(autoincrement())
name String?
}

屬性

屬性修改欄位或塊(例如模型)的行為。有兩種方法可以向資料模型新增屬性

  • 欄位屬性以 @ 為字首
  • 屬性以 @@ 為字首

某些屬性接受引數。屬性中的引數始終是命名的,但在大多數情況下,可以省略引數名稱

注意:簽名中的前導下劃線表示可以省略引數名稱

@id

在模型上定義單欄位 ID。

備註

通用
  • 不能在關係欄位上定義
  • 不能是可選的
關係型資料庫
MongoDB
  • 對應的資料庫構造:任何有效的 BSON 型別,陣列除外

  • 每個模型必須定義一個 @id 欄位

  • 底層 ID 欄位名稱始終是 _id,並且必須使用 @map("_id") 進行對映

  • 可以在任何標量欄位上定義(StringIntenum),除非您想在資料庫中使用 ObjectId

  • 要使用 ObjectId 作為您的 ID,您必須

    • 使用 StringBytes 欄位型別

    • 使用 @db.ObjectId 註解您的欄位

      id   String  @db.ObjectId  @map("_id")
    • (可選)使用 @default 屬性註解您的欄位,該屬性使用 auto() 函式自動生成 ObjectId

      id   String  @db.ObjectId  @map("_id") @default(auto())
  • 支援 cuid()uuid()ulid(),但它們不會生成有效的 ObjectId —— 請改用 auto() 作為 @id

  • 不支援 autoincrement()

引數

名稱必需型別描述
mapString資料庫中底層主鍵約束的名稱。

MySQL 或 MongoDB 不支援。
lengthnumber允許您為要索引值的子部分指定最大長度。

僅適用於 MySQL。在 3.5.0 及更高版本中處於預覽階段,在 4.0.0 及更高版本中普遍可用。
sortString允許您指定 ID 條目在資料庫中的儲存順序。可用選項為 AscDesc

僅適用於 SQL Server。在 3.5.0 及更高版本中處於預覽階段,在 4.0.0 及更高版本中普遍可用。
clusteredBoolean定義 ID 是聚集索引還是非聚集索引。預設為 true

僅適用於 SQL Server。在 3.13.0 及更高版本中處於預覽階段,在 4.0.0 及更高版本中普遍可用。

簽名

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

注意:在版本 4.0.0 之前,或在啟用 extendedIndexes 預覽功能且版本為 3.5.0 時,簽名為

@id(map: String?)

注意:在版本 3.0.0 之前,簽名為

@id

示例

在大多數情況下,您希望資料庫建立 ID。為此,請使用 @default 屬性註解 ID 欄位,並使用函式初始化該欄位。

生成自增整數作為 ID(僅限關係型資料庫)
model User {
id Int @id @default(autoincrement())
name String
}
生成 ObjectId 作為 ID(僅限 MongoDB)
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
}
生成 cuid() 值作為 ID
model User {
id String @id @default(cuid())
name String
}
生成 uuid() 值作為 ID
model User {
id String @id @default(uuid())
name String
}
生成 ulid() 值作為 ID
model User {
id String @id @default(ulid())
name String
}
沒有預設值的單欄位 ID

在以下示例中,id 沒有預設值

model User {
id String @id
name String
}

請注意,在上述情況下,您必須在使用 Prisma Client 為 User 模型建立新記錄時提供自己的 ID 值,例如

const newUser = await prisma.user.create({
data: {
id: 1,
name: "Alice",
},
});
在沒有預設值的關係標量欄位上指定 ID

在以下示例中,authorId 既是關係標量又是 Profile 的 ID

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 Client 的巢狀寫入來建立 User 將配置檔案連線到現有使用者。

以下示例建立了一個使用者和一個配置檔案

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.",
},
},
},
});

以下示例將新配置檔案連線到使用者

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

警告

MongoDB 不支援
MongoDB 聯結器不支援複合 ID。

在模型上定義多欄位 ID(複合 ID)。

備註

  • 對應的資料庫型別:PRIMARY KEY
  • 可以使用 @default 屬性進行註解,該屬性使用函式自動生成 ID
  • 不能是可選的
  • 可以在任何標量欄位上定義(StringIntenum
  • 不能在關係欄位上定義
  • Prisma Client 中複合 ID 欄位的命名模式如下:field1_field2_field3

引數

名稱必需型別描述
fieldsFieldReference[]欄位名稱列表——例如 ["firstname", "lastname"]
nameStringPrisma Client 將為涵蓋所有欄位的引數公開的名稱,例如 fullName: { firstName: "First", lastName: "Last"} 中的 fullName
mapString資料庫中底層主鍵約束的名稱。

MySQL 不支援。
lengthnumber允許您為要索引值的子部分指定最大長度。

僅適用於 MySQL。在 3.5.0 及更高版本中處於預覽階段,在 4.0.0 及更高版本中普遍可用。
sortString允許您指定 ID 條目在資料庫中的儲存順序。可用選項為 AscDesc

僅適用於 SQL Server。在 3.5.0 及更高版本中處於預覽階段,在 4.0.0 及更高版本中普遍可用。
clusteredBoolean定義 ID 是聚集索引還是非聚集索引。預設為 true

僅適用於 SQL Server。在 3.13.0 及更高版本中處於預覽階段,在 4.0.0 及更高版本中普遍可用。

可以省略 @@id 屬性上 fields 引數的名稱

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

簽名

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

注意:直到版本 3.0.0,簽名為

@@id(_ fields: FieldReference[])

示例

在兩個 String 欄位上指定多欄位 ID(僅限關係型資料庫)
model User {
firstName String
lastName String
email String @unique
isAdmin Boolean @default(false)

@@id([firstName, lastName])
}

建立使用者時,您必須提供 firstNamelastName 的唯一組合

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

要檢索使用者,請使用生成的複合 ID 欄位(firstName_lastName

const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: "Alice",
lastName: "Smith",
},
},
});
在兩個 String 欄位和一個 Boolean 欄位上指定多欄位 ID(僅限關係型資料庫)
model User {
firstName String
lastName String
email String @unique
isAdmin Boolean @default(false)

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

現在,在建立新的 User 記錄時,您必須為 firstNamelastNameisAdmin 提供唯一的組合值

const user = await prisma.user.create({
data: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
});
指定包含關係欄位的多欄位 ID(僅限關係型資料庫)
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 提供唯一的組合值

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

@default

定義欄位的預設值

備註

  • 尚不能在 Prisma schema 中表示的預設值,在使用內省時由 dbgenerated() 函式表示。
  • Prisma schema 中的關係欄位不允許使用預設值。但請注意,您仍然可以在支援關係的欄位(@relation 屬性中 fields 引數中列出的欄位)上定義預設值。關係支援欄位上的預設值意味著該關係將自動為您填充。
  • 在原生支援標量列表的資料庫中,預設值可與標量列表一起使用。
關係型資料庫
  • 對應的資料庫構造:DEFAULT
  • 預設值可以是靜態值(4, "hello")或以下函式之一
  • 尚不能在 Prisma schema 中表示的預設值,在使用內省時由 dbgenerated(...) 函式表示。
  • Prisma schema 中的關係欄位不允許使用預設值。但請注意,您仍然可以在支援關係的欄位(@relation 屬性中 fields 引數中列出的欄位)上定義預設值。關係支援欄位上的預設值意味著該關係將自動為您填充。
  • 在原生支援標量列表的資料庫中,預設值可與標量列表一起使用。
  • JSON 資料。請注意,JSON 需要在 @default 屬性中用雙引號括起來,例如:@default("[]")。如果您想提供一個 JSON 物件,您需要用雙引號括起來,然後使用反斜槓轉義所有內部雙引號,例如:@default("{ \"hello\": \"world\" }")
MongoDB

引數

名稱必需型別描述
value一個表示式(例如 5truenow()
mapString僅限 SQL Server。

可以省略 @default 屬性上 value 引數的名稱

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

簽名

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

注意:直到版本 3.0.0,簽名為

@default(_ value: Expression)

示例

Int 的預設值
model User {
email String @unique
profileViews Int @default(0)
}
Float 的預設值
model User {
email String @unique
number Float @default(1.1)
}
Decimal 的預設值
model User {
email String @unique
number Decimal @default(22.99)
}
BigInt 的預設值
model User {
email String @unique
number BigInt @default(34534535435353)
}
String 的預設值
model User {
email String @unique
name String @default("")
}
Boolean 的預設值
model User {
email String @unique
isAdmin Boolean @default(false)
}
DateTime 的預設值

請注意,DateTime 的靜態預設值基於 ISO 8601 標準。

model User {
email String @unique
data DateTime @default("2020-03-19T14:21:00+02:00")
}
Bytes 的預設值
model User {
email String @unique
secret Bytes @default("SGVsbG8gd29ybGQ=")
}
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?
}
標量列表的預設值
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

為此欄位定義唯一約束。

備註

通用
  • 使用 @unique 註解的欄位可以是可選的或必需的
  • 如果一個模型沒有 @id / @@id 並且該欄位代表模型上唯一的唯一約束,則使用 @unique 註解的欄位必須是必需的
  • 一個模型可以有任意數量的唯一約束
  • 可以在任何標量欄位上定義
  • 不能在關係欄位上定義
關係型資料庫
  • 對應的資料庫構造:UNIQUE
  • NULL 值被認為是不同的(允許同一列中存在多個具有 NULL 值的行)
  • 新增唯一約束會自動為指定的列新增相應的唯一索引
MongoDB

引數

名稱必需型別描述
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(map: String?, length: number?, sort: String?)

注意:在版本 4.0.0 之前,或在啟用 extendedIndexes 預覽功能且版本為 3.5.0 時,簽名為

@unique(map: String?)

注意:在版本 3.0.0 之前,簽名為

@unique

示例

在必需的 String 欄位上指定唯一屬性
model User {
email String @unique
name String
}
在可選的 String 欄位上指定唯一屬性
model User {
id Int @id @default(autoincrement())
email String? @unique
name String
}
在關係標量欄位 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() 值作為預設值的唯一屬性
model User {
token String @unique @default(cuid())
name String
}

@@unique

為指定欄位定義複合唯一約束

備註

通用
  • 構成唯一約束的所有欄位必須是必填欄位。以下模型無效,因為 id 可能為 null

    model User {
    firstname Int
    lastname Int
    id Int?

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

    這種行為的原因是所有聯結器都將 null 值視為不同的,這意味著兩行看起來相同的資料也被認為是唯一的

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

關係型資料庫
  • 對應的資料庫構造:UNIQUE
  • 如果 @@unique 塊代表沒有 @id / @@id 的模型上唯一的唯一約束,則它是必需的
  • 新增唯一約束會自動為指定的列新增相應的唯一索引
MongoDB
  • MongoDB 中的複合索引 強制執行
  • @@unique 塊不能作為模型的唯一識別符號使用 —— MongoDB 需要一個 @id 欄位

引數

名稱必需型別描述
fieldsFieldReference[]欄位名稱列表——例如 ["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 引數的名稱

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

lengthsort 引數被新增到相關欄位名稱中

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

簽名

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

注意:在版本 4.0.0 之前,或在啟用 extendedIndexes 預覽功能且版本為 3.5.0 之前,簽名為

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

注意:在版本 3.0.0 之前,簽名為

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

示例

在兩個 String 欄位上指定多欄位唯一屬性
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)

@@unique([firstName, lastName])
}

要檢索使用者,請使用生成的欄位名稱(firstname_lastname

const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
},
});
在兩個 String 欄位和一個 Boolean 欄位上指定多欄位唯一屬性
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)

@@unique([firstName, lastName, isAdmin])
}
指定包含關係欄位的多欄位唯一屬性
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
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)

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

要檢索使用者,請使用自定義欄位名稱(admin_identifier

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

@@index

在資料庫中定義索引。

備註

關係型資料庫
  • 對應的資料庫構造:INDEX
  • 還有一些額外的索引配置選項尚不能透過 Prisma schema 提供。這些選項包括
    • PostgreSQL 和 CockroachDB
      • 將索引欄位定義為表示式(例如 CREATE INDEX title ON public."Post"((lower(title)) text_ops);
      • 使用 WHERE 定義部分索引
      • 使用 CONCURRENTLY 併發建立索引
資訊

雖然您無法在 Prisma schema 中配置這些選項,但您仍然可以直接在資料庫級別進行配置。

MongoDB
  • 在版本 3.12.0 及更高版本中,您可以使用語法 @@index([compositeType.field])複合型別的欄位上定義索引。有關更多詳細資訊,請參閱定義複合型別索引

引數

名稱必需型別描述
fieldsFieldReference[]欄位名稱列表——例如 ["firstname", "lastname"]
nameStringPrisma Client 將為涵蓋所有欄位的引數公開的名稱,例如 fullName: { firstName: "First", lastName: "Last"} 中的 fullName
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 引數的名稱

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

lengthsort 引數被新增到相關欄位名稱中

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

簽名

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

注意:直到版本 3.0.0,簽名為

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

舊的 name 引數仍將被接受,以避免破壞性更改。

示例

假設您想為 Post 模型的 title 欄位新增索引

定義單列索引(僅限關係型資料庫)
model Post {
id Int @id @default(autoincrement())
title String
content String?

@@index([title])
}
定義多列索引(僅限關係型資料庫)
model Post {
id Int @id @default(autoincrement())
title String
content String?

@@index([title, content])
}
定義一個帶名稱的索引(僅限關係型資料庫)
model Post {
id Int @id @default(autoincrement())
title String
content String?

@@index(fields: [title, content], name: "main_index")
}
在一個複合型別欄位上定義索引(僅限關係型資料庫)
type Address {
street String
number Int
}

model User {
id Int @id
email String
address Address

@@index([address.number])
}

@relation

定義關係的元資訊。瞭解更多

備註

關係型資料庫
  • 對應的資料庫構造: FOREIGN KEY / REFERENCES
MongoDB
  • 如果你的模型主鍵在底層資料庫中是 ObjectId 型別,那麼主鍵外部索引鍵都必須有 @db.ObjectId 屬性

引數

名稱型別必需描述示例
nameString有時(例如,為了消除關係的歧義)定義關係的名稱。在多對多關係中,它也決定了底層關係表的名稱。"CategoryOnPost", "MyRelation"
fieldsFieldReference[]註解的關係欄位上當前模型的欄位列表["authorId"], ["authorFirstName, authorLastName"]
引用FieldReference[]註解的關係欄位上關係另一側模型的欄位列表["id"], ["firstName, lastName"]
mapString為資料庫中的外部索引鍵定義自定義名稱["id"], ["firstName, lastName"]
onUpdate列舉。有關值,請參閱引用操作型別定義當被引用模型中的引用條目被更新時執行的引用操作Cascade, NoAction
onDelete列舉。有關值,請參閱引用操作型別定義當被引用模型中的引用條目被刪除時執行的引用操作Cascade, NoAction

@relation 屬性上的 name 引數的名稱可以省略(references 是必需的)

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

// or

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

簽名

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

對於 SQLite,簽名變為

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

注意:直到版本 3.0.0,簽名為

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

示例

參見:@relation 屬性

@map

將 Prisma schema 中的欄位名或列舉值對映到資料庫中具有不同名稱的列或文件欄位。如果你不使用 @map,Prisma 欄位名將與列名或文件欄位名完全匹配。

請參閱使用自定義模型和欄位名稱,瞭解 @map@@map 如何更改生成的 Prisma Client。

備註

通用
MongoDB

你的 @id 欄位必須包含 @map("_id")。例如

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

引數

名稱型別必需描述示例
nameString資料庫列(關係型資料庫)或文件欄位(MongoDB)的名稱。"comments", "someFieldName"

@map 屬性上的 name 引數的名稱可以省略

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

簽名

@map(_ name: String)

示例

firstName 欄位對映到名為 first_name 的列
model User {
id Int @id @default(autoincrement())
firstName String @map("first_name")
}

生成的客戶端

await prisma.user.create({
data: {
firstName: "Yewande", // first_name --> firstName
},
});
將名為 ADMIN 的列舉對映到名為 admin 的資料庫列舉
enum Role {
ADMIN @map("admin")
CUSTOMER
}

@@map

將 Prisma schema 模型名稱對映到具有不同名稱的表(關係型資料庫)或集合(MongoDB),或將列舉名稱對映到資料庫中不同的底層列舉。如果你不使用 @@map,模型名稱將與表(關係型資料庫)或集合(MongoDB)名稱完全匹配。

請參閱使用自定義模型和欄位名稱,瞭解 @map@@map 如何更改生成的 Prisma Client。

引數

名稱型別必需描述示例
nameString資料庫表(關係型資料庫)或集合(MongoDB)的名稱。"comments", "someTableOrCollectionName"

@@map 屬性上的 name 引數的名稱可以省略

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

簽名

@@map(_ name: String)

示例

User 模型對映到名為 users 的資料庫表/集合
model User {
id Int @id @default(autoincrement())
name String

@@map("users")
}

生成的客戶端

await prisma.user.create({
// users --> user
data: {
name: "Yewande",
},
});
Role 列舉對映到資料庫中名為 _Role 的原生列舉,並將其值對映到資料庫中的小寫值
enum Role {
ADMIN @map("admin")
CUSTOMER @map("customer")

@@map("_Role")
}

@updatedAt

自動儲存記錄上次更新的時間。如果你沒有自己提供時間,Prisma Client 將自動為具有此屬性的欄位設定值。

備註

  • 相容 DateTime 欄位
  • 在 Prisma ORM 層面實現
警告

4.4.0 版本之前,如果你還使用了 now(),如果你的資料庫和應用程式有不同的時區,時間可能會與 @updatedAt 值不同。這是因為 @updatedAt 在 Prisma ORM 層面操作,而 now() 在資料庫層面操作。

注意

如果你傳入一個空的更新子句,@updatedAt 值將保持不變。例如

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

引數

不適用

簽名

@updatedAt

示例

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

@ignore

@ignore 新增到你希望從 Prisma Client 中排除的欄位(例如,你不希望 Prisma Client 使用者更新的欄位)。被忽略的欄位將從生成的 Prisma Client 中排除。當對沒有 @default必填欄位執行此操作時,模型的 create 方法會被停用(因為資料庫無法在沒有該資料的情況下建立條目)。

備註

  • 2.17.0 版本及更高版本中,當你進行內省時,Prisma ORM 會自動將 @ignore 新增到引用無效模型的欄位。

示例

以下示例演示了手動新增 @ignore 以將 email 欄位從 Prisma Client 中排除

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

@@ignore

@@ignore 新增到你希望從 Prisma Client 中排除的模型(例如,你不希望 Prisma 使用者更新的模型)。被忽略的模型將從生成的 Prisma Client 中排除。

備註

  • 2.17.0 版本及更高版本中,Prisma ORM 會將 @@ignore 新增到無效模型。(它還會將 @ignore 新增到指向此類模型的關係)

示例

在以下示例中,Post 模型無效,因為它沒有唯一識別符號。使用 @@ignore 將其從生成的 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 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

警告

要使用此屬性,你必須啟用 multiSchema 預覽功能。目前,PostgreSQL、CockroachDB 和 SQL Server 聯結器支援多個數據庫 schema。

@@schema 新增到模型以指定資料庫中哪個 schema 應包含與該模型關聯的表。

引數

名稱型別必需描述示例
nameString資料庫 schema 的名稱。"base", "auth"

@@schema 屬性上的 name 引數的名稱可以省略

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

簽名

@@schema(_ name: String)

示例

User 模型對映到名為 auth 的資料庫 schema
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")
}
資訊

有關使用 multiSchema 功能的更多資訊,請參閱本指南

@shardKey

注意

此功能要求你的 generator 中啟用 shardKeys 預覽功能標誌

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

@shardKey 屬性僅與 PlanetScale 資料庫相容。它允許你在模型的欄位上定義分片鍵

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

@@shardKey

注意

此功能要求你的 generator 中啟用 shardKeys 預覽功能標誌

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

@shardKey 屬性僅與 PlanetScale 資料庫相容。它允許你在模型的多個欄位上定義分片鍵

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

屬性函式

auto()

警告
此函式僅在 MongoDB 上可用。

表示由資料庫自動生成的預設值

備註

MongoDB

用於為 @id 欄位生成 ObjectId

id  String  @map("_id") @db.ObjectId @default(auto())
關係型資料庫

auto() 函式在關係型資料庫中不可用。

示例

生成 ObjectId(僅限 MongoDB)
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String?
}

autoincrement()

警告

MongoDB 不支援
MongoDB 聯結器不支援 autoincrement() 函式。

在底層資料庫中建立整數序列,並根據該序列將遞增的值分配給所建立記錄的 ID 值。

備註

示例

生成自增整數作為 ID(僅限關係型資料庫)
model User {
id Int @id @default(autoincrement())
name String
}

sequence()

資訊

僅由 CockroachDB 支援
sequence 函式僅由 CockroachDB 聯結器支援。

在底層資料庫中建立整數序列,並根據該序列將遞增的值分配給所建立記錄的值。

可選引數

引數示例
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

示例

生成遞增整數作為 ID
model User {
id Int @id @default(sequence(maxValue: 4294967295))
name String
}

cuid()

根據 cuid 規範生成全域性唯一識別符號。

如果你想使用 cuid2,你可以將 2 作為引數傳遞給 cuid 函式:cuid(2)

備註

  • String 相容。
  • 由 Prisma ORM 實現,因此在底層資料庫 schema 中不可“見”。在使用內省時,你仍然可以透過手動更改 Prisma schema生成 Prisma Client 來使用 cuid(),在這種情況下,值將由 Prisma 的查詢引擎生成。
  • 由於 cuid() 輸出的長度根據 cuid 建立者的說法是未定義的,因此安全的欄位大小為 30 個字元,以允許足夠的字元來表示非常大的值。如果你將欄位大小設定為小於 30,然後 cuid() 生成了更大的值,你可能會看到 Prisma Client 錯誤,例如 Error: The provided value for the column is too long for the column's type.
  • 對於 MongoDBcuid() 不會生成有效的 ObjectId。如果你想在底層資料庫中使用 ObjectId,可以使用@db.ObjectId 語法。但是,如果你的 _id 欄位不是 ObjectId 型別,你仍然可以使用 cuid()

示例

生成 cuid() 值作為 ID
model User {
id String @id @default(cuid())
name String
}
根據 cuid2 規範生成 cuid(2) 值作為 ID
model User {
id String @id @default(cuid(2))
name String
}

uuid()

根據 UUID 規範生成全域性唯一識別符號。Prisma ORM 支援版本 4(預設)和 7。

備註

  • String 相容。
  • 由 Prisma ORM 實現,因此在底層資料庫 schema 中不可“見”。在使用內省時,你仍然可以透過手動更改 Prisma schema生成 Prisma Client 來使用 uuid(),在這種情況下,值將由 Prisma ORM 的查詢引擎生成。
  • 對於關係型資料庫:如果你不想使用 Prisma ORM 的 uuid() 函式,可以使用帶有 dbgenerated 的原生資料庫函式
  • 對於 MongoDBuuid() 不會生成有效的 ObjectId。如果你想在底層資料庫中使用 ObjectId,可以使用@db.ObjectId 語法。但是,如果你的 _id 欄位不是 ObjectId 型別,你仍然可以使用 uuid()

示例

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

ulid()

根據 ULID 規範生成全域性唯一的、可按字典序排序的識別符號。

備註

  • ulid() 將生成 128 位隨機識別符號,表示為 26 個字元長的字母數字字串,例如:01ARZ3NDEKTSV4RRFFQ69G5FAV

示例

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

nanoid()

根據 Nano ID 規範生成值。nanoid() 接受一個介於 2 到 255 之間的整數值,該值指定生成 ID 值的長度,例如 nanoid(16) 將生成 16 個字元的 ID。如果你不為 nanoid() 函式提供值,則預設值為 21。

資訊

Nano ID 與 UUID v4(基於隨機)相當。它在 ID 中具有相似數量的隨機位(Nano ID 為 126 位,UUID 為 122 位),因此具有相似的衝突機率

要使重複的機率達到十億分之一,必須生成 103 萬億個版本 4 ID。

Nano ID 和 UUID v4 之間有兩個主要區別

  • Nano ID 使用更大的字母表,因此相似數量的隨機位僅包含在 21 個符號中,而不是 36 個。
  • Nano ID 程式碼比 uuid/v4 包小 4 倍:130 位元組而不是 423 位元組。

備註

  • String 相容。
  • 由 Prisma ORM 實現,因此在底層資料庫 schema 中不可“見”。在使用內省時,你仍然可以透過手動更改 Prisma schema生成 Prisma Client 來使用 uuid(),在這種情況下,值將由 Prisma ORM 的查詢引擎生成。
  • 對於 MongoDBnanoid() 不會生成有效的 ObjectId。如果你想在底層資料庫中使用 ObjectId,可以使用@db.ObjectId 語法。但是,如果你的 _id 欄位不是 ObjectId 型別,你仍然可以使用 nanoid()

示例

生成 21 個字元的 nanoid() 值作為 ID
model User {
id String @id @default(nanoid())
name String
}
生成 16 個字元的 nanoid() 值作為 ID
model User {
id String @id @default(nanoid(16))
name String
}

now()

設定記錄建立時的時間戳。

備註

通用
警告

4.4.0 版本之前,如果你還使用了 @updatedAt,如果你的資料庫和應用程式有不同的時區,時間可能會與 now() 值不同。這是因為 @updatedAt 在 Prisma ORM 層面操作,而 now() 在資料庫層面操作。

關係型資料庫
  • 在資料庫級別實現,這意味著它體現在資料庫 schema 中,並且可以透過內省識別。資料庫實現

    資料庫實現
    PostgreSQLCURRENT_TIMESTAMP 及其別名,如 now()
    MySQLCURRENT_TIMESTAMP 及其別名,如 now()
    SQLiteCURRENT_TIMESTAMP 及其別名,如 date('now')
    CockroachDBCURRENT_TIMESTAMP 及其別名,如 now()
MongoDB
  • 在 Prisma ORM 層面實現

示例

設定記錄建立時的當前時間戳值
model User {
id String @id
createdAt DateTime @default(now())
}

dbgenerated(...)

表示 Prisma schema 中無法表達的預設值(例如 random())。

備註

關係型資料庫

示例

Unsupported 型別設定預設值
circle     Unsupported("circle")?   @default(dbgenerated("'<(10,4),11>'::circle"))
覆蓋受支援型別的預設值行為

你還可以使用 dbgenerated(...) 為支援的型別設定預設值。例如,在 PostgreSQL 中,你可以在資料庫級別生成 UUID,而不是依賴 Prisma ORM 的 uuid()

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

注意gen_random_uuid() 是 PostgreSQL 函式。要在 PostgreSQL 12.13 及更早版本中使用它,你必須啟用 pgcrypto 擴充套件。

在 Prisma ORM 4.5.0 及更高版本中,你可以使用postgresqlExtensions 預覽功能在 Prisma schema 中宣告 pgcrypto 擴充套件。

屬性引數型別

FieldReference[]

欄位名稱陣列:[id], [firstName, lastName]

String

雙引號中的變長文字:"", "Hello World", "Alice"

Expression

Prisma ORM 可以評估的表示式:42.0, "", Bob, now(), cuid()

enum

警告

不支援 Microsoft SQL Server
Microsoft SQL Server 聯結器不支援 enum 型別。

定義列舉

備註

  • 列舉 natively supported by PostgreSQL and MySQL
  • 列舉在 SQLite 和 MongoDB 中透過 Prisma ORM 層實現和強制執行

命名約定

  • 列舉名稱必須以字母開頭(通常使用PascalCase拼寫)
  • 列舉必須使用單數形式(例如 Role 而不是 rolerolesRoles)。
  • 必須遵循以下正則表示式:[A-Za-z][A-Za-z0-9_]*

示例

指定一個具有兩個可能值的 enum

enum Role {
USER
ADMIN
}

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

指定一個具有兩個可能值並設定預設值的 enum

enum Role {
USER
ADMIN
}

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

type

警告

複合型別僅適用於 MongoDB

資訊

複合型別在 3.12.0 及更高版本中可用,如果你啟用了 mongodb 預覽功能標誌,則在 3.10.0 及更高版本中可用。

定義一個複合型別

命名約定

型別名稱必須

  • 以字母開頭(通常使用PascalCase拼寫)
  • 符合以下正則表示式:[A-Za-z][A-Za-z0-9_]*

示例

定義一個包含 Photo 複合型別列表的 Product 模型

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

type Photo {
height Int
width Int
url String
}
© . This site is unofficial and not affiliated with Prisma Data, Inc.