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。從 5.1.0 版本開始,Prisma Studio 支援 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 預覽版。 |
以下 provider 可用
備註🔗
- 在一個 schema 中,您只能有 一個
datasource
區塊。 datasource db
是一種慣例 - 但是,您可以為您的資料來源指定任何名稱 - 例如,datasource mysql
或datasource 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 中定義產生器。
欄位🔗
generator
區塊接受以下欄位
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
provider | 是 | 字串(檔案路徑)或列舉 (prisma-client-js ) | 描述要使用哪個產生器。這可以指向實現產生器的檔案,或直接指定內建產生器。 |
output | 否 | 字串(檔案路徑) | 決定產生用戶端的所在位置,了解更多。預設值:node_modules/.prisma/client |
previewFeatures | 否 | 列舉列表 | 使用 intellisense 查看目前可用的預覽功能列表(在 Visual Studio Code 中使用 Ctrl+Space )預設值:無 |
engineType | 否 | 列舉 (library 或 binary ) | 定義要下載和使用的查詢引擎類型。預設值:library |
binaryTargets | 否 | 列舉列表(見下文) | 指定 Prisma Client 將在其上運行的作業系統,以確保查詢引擎的相容性。預設值:native |
binaryTargets
選項🔗
下表列出了所有支援的作業系統以及在 binaryTargets
中指定的平台名稱。
除非另有說明,否則預設支援的 CPU 架構為 x86_64。
macOS🔗
建置 OS | Prisma 引擎建置名稱 |
---|---|
macOS Intel x86_64 | darwin |
macOS ARM64 | darwin-arm64 |
Windows🔗
建置 OS | Prisma 引擎建置名稱 |
---|---|
Windows | windows |
Linux (Alpine on x86_64 architectures)🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Alpine (3.17 及更新版本) | linux-musl-openssl-3.0.x * | 3.0.x |
Alpine (3.16 及更舊版本) | linux-musl | 1.1.x |
* 適用於 Prisma ORM 4.8.0 及更高版本。
Linux (Alpine on ARM64 architectures)🔗
建置 OS | 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🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Debian 8 (Jessie) | debian-openssl-1.0.x | 1.0.x |
Debian 9 (Stretch) | debian-openssl-1.1.x | 1.1.x |
Debian 10 (Buster) | debian-openssl-1.1.x | 1.1.x |
Debian 11 (Bullseye) | debian-openssl-1.1.x | 1.1.x |
Debian 12 (Bookworm) | debian-openssl-3.0.x | 3.0.x |
Linux (Ubuntu), x86_64🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Ubuntu 14.04 (trusty) | debian-openssl-1.0.x | 1.0.x |
Ubuntu 16.04 (xenial) | debian-openssl-1.0.x | 1.0.x |
Ubuntu 18.04 (bionic) | debian-openssl-1.1.x | 1.1.x |
Ubuntu 19.04 (disco) | debian-openssl-1.1.x | 1.1.x |
Ubuntu 20.04 (focal) | debian-openssl-1.1.x | 1.1.x |
Ubuntu 21.04 (hirsute) | debian-openssl-1.1.x | 1.1.x |
Ubuntu 22.04 (jammy) | debian-openssl-3.0.x | 3.0.x |
Ubuntu 23.04 (lunar) | debian-openssl-3.0.x | 3.0.x |
Linux (CentOS), x86_64🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
CentOS 7 | rhel-openssl-1.0.x | 1.0.x |
CentOS 8 | rhel-openssl-1.1.x | 1.1.x |
Linux (Fedora), x86_64🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Fedora 28 | rhel-openssl-1.1.x | 1.1.x |
Fedora 29 | rhel-openssl-1.1.x | 1.1.x |
Fedora 30 | rhel-openssl-1.1.x | 1.1.x |
Fedora 36 | rhel-openssl-3.0.x | 3.0.x |
Fedora 37 | rhel-openssl-3.0.x | 3.0.x |
Fedora 38 | rhel-openssl-3.0.x | 3.0.x |
Linux (Linux Mint), x86_64🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Linux Mint 18 | debian-openssl-1.0.x | 1.0.x |
Linux Mint 19 | debian-openssl-1.1.x | 1.1.x |
Linux Mint 20 | debian-openssl-1.1.x | 1.1.x |
Linux Mint 21 | debian-openssl-3.0.x | 3.0.x |
Linux (Arch Linux), x86_64🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Arch Linux 2019.09.01 | debian-openssl-1.1.x | 1.1.x |
Arch Linux 2023.04.23 | debian-openssl-3.0.x | 3.0.x |
Linux ARM64 (所有主要發行版,但 Alpine 除外)🔗
建置 OS | Prisma 引擎建置名稱 | OpenSSL |
---|---|---|
Linux ARM64 glibc-based 發行版 | linux-arm64-openssl-1.0.x | 1.0.x |
Linux ARM64 glibc-based 發行版 | linux-arm64-openssl-1.1.x | 1.1.x |
Linux ARM64 glibc-based 發行版 | linux-arm64-openssl-3.0.x | 3.0.x |
範例🔗
指定具有預設 output
、previewFeatures
、engineType
和 binaryTargets
的 prisma-client-js
產生器🔗
generator client {
provider = "prisma-client-js"
}
請注意,上述 generator
定義與以下內容等效,因為它使用了 output
、engineType
和 binaryTargets
的預設值(以及隱含的 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
以確保與 OS 的相容性🔗
此範例示範如何根據上方的表格,將 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
而不是user
、users
或Users
) - Prisma ORM 有許多 保留字,這些保留字在 Prisma ORM 內部使用,因此不能用作模型名稱。您可以在此處 和 此處找到保留字。
注意:您可以使用
@@map
屬性 將模型(例如,User
)對應到具有不同名稱且不符合模型命名慣例的表格(例如,users
)。
欄位順序🔗
- 在 2.3.0 及更高版本中,內省會以與資料庫中對應欄相同的順序,列出模型欄位。關聯欄位列在純量欄位之後。
範例🔗
名為 User
且具有兩個純量欄位的模型🔗
- 關聯式資料庫
- MongoDB
model User {
email String @unique // `email` can not be optional because it's the only unique field on the model
name String?
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
}
model
欄位🔗
欄位是模型的屬性。
備註🔗
命名慣例🔗
- 必須以字母開頭
- 通常以 camelCase 拼寫
- 必須遵循以下正規表示式:
[A-Za-z][A-Za-z0-9_]*
注意:您可以使用
@map
屬性 將欄位名稱對應到具有不同名稱且不符合欄位命名慣例的欄位:例如myField @map("my_field")
。
model
欄位純量類型🔗
資料來源連接器 決定每個 Prisma ORM 純量類型對應到哪個原生資料庫類型。同樣地,產生器 決定這些類型中的每一個對應到目標程式語言中的哪個類型。
Prisma 模型也具有定義模型之間關係的模型欄位類型。
String
🔗
變長文字。
預設類型對應🔗
連接器 | 預設對應 |
---|---|
PostgreSQL | text |
SQL Server | nvarchar(1000) |
MySQL | varchar(191) |
MongoDB | 字串 |
SQLite | TEXT |
CockroachDB | STRING |
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🔗
字串
原生資料庫類型屬性 | 註解 |
---|---|
@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 |
請注意,CockroachDB 目前不支援 PostgreSQL 中支援的 xml
和 citext
類型。
用戶端🔗
Prisma Client JS |
---|
string |
Boolean
🔗
真值或假值。
預設類型對應🔗
連接器 | 預設對應 |
---|---|
PostgreSQL | boolean |
SQL Server | bit |
MySQL | TINYINT(1) |
MongoDB | Bool |
SQLite | INTEGER |
CockroachDB | BOOL |
PostgreSQL🔗
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
boolean | @db.Boolean |
MySQL🔗
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
TINYINT(1) | @db.TinyInt(1) | 如果最大長度大於 1(例如 TINYINT(2) ),或預設值不是 1 、0 或 NULL 以外的任何值,則 TINYINT 會對應到 Int |
BIT(1) | @db.Bit |
MongoDB🔗
Bool
Microsoft SQL Server🔗
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
bit | @db.Bit |
SQLite🔗
INTEGER
CockroachDB🔗
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
BOOL | @db.Bool |
用戶端🔗
Prisma Client JS |
---|
boolean |
Int
🔗
預設類型對應🔗
連接器 | 預設對應 |
---|---|
PostgreSQL | integer |
SQL Server | int |
MySQL | INT |
MongoDB | Int |
SQLite | INTEGER |
CockroachDB | INT |
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) ),或預設值不是 1 、0 或 NULL 以外的任何值,則 TINYINT 會對應到 Int 。TINYINT(1) 會對應到 Boolean 。 |
TINYINT UNSIGNED | @db.UnsignedTinyInt | TINYINT(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 中,integer 和 int 是 int4 的別名,並對應到 @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
🔗
BigInt
在 2.17.0 及更高版本中可用。
預設類型對應🔗
連接器 | 預設對應 |
---|---|
PostgreSQL | bigint |
SQL Server | int |
MySQL | BIGINT |
MongoDB | Long |
SQLite | INTEGER |
CockroachDB | INTEGER |
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 中,int 是 int4 的別名 |
bigserial | serial8 | @db.Int8 @default(autoincrement()) |
用戶端
用戶端 | 類型 | 描述 |
---|---|---|
Prisma Client JS | BigInt | 請參閱使用 BigInt 的範例 |
Float
浮點數。
Float
在 2.17.0 及更高版本中對應到Double
- 請參閱發行說明 和影片:Prisma ORM 2.17.0 中 Float 預設對應的變更 以取得關於此變更的更多資訊。
預設類型對應
連接器 | 預設對應 |
---|---|
PostgreSQL | double precision(雙倍精確度) |
SQL Server | float(53) |
MySQL | DOUBLE |
MongoDB | Double(雙精度浮點數) |
SQLite | REAL |
CockroachDB | DOUBLE 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
預設類型對應
連接器 | 預設對應 |
---|---|
PostgreSQL | decimal(65,30) |
SQL Server | decimal(32,16) |
MySQL | DECIMAL(65,30) |
MongoDB | 不支援 |
SQLite | DECIMAL |
CockroachDB | DECIMAL |
PostgreSQL
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
decimal | numeric | @db.Decimal(p, s) † | |
money(貨幣) | @db.Money |
- †
p
(precision,精確度),要儲存的最大總位數。s
(scale,小數位數),小數點右邊要儲存的位數。
MySQL
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
DECIMAL | NUMERIC | @db.Decimal(p, s) † |
- †
p
(precision,精確度),要儲存的最大總位數。s
(scale,小數位數),小數點右邊要儲存的位數。
MongoDB
不支援.
Microsoft SQL Server
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
decimal | numeric | @db.Decimal(p, s) † |
- †
p
(precision,精確度),要儲存的最大總位數。s
(scale,小數位數),小數點右邊要儲存的位數。
SQLite
DECIMAL
(在 2.17.0 版本中從 REAL
變更)
CockroachDB
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
DECIMAL | DEC | NUMERIC | @db.Decimal(p, s) † | |
money(貨幣) | 尚未 | CockroachDB 尚不支援 PostgreSQL 的 money 類型 |
- †
p
(precision,精確度),要儲存的最大總位數。s
(scale,小數位數),小數點右邊要儲存的位數。
用戶端
用戶端 | 類型 | 描述 |
---|---|---|
Prisma Client JS | Decimal(十進制數) | 請參閱使用 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
。
預設類型對應
連接器 | 預設對應 |
---|---|
PostgreSQL | timestamp(3) |
SQL Server | datetime2 |
MySQL | DATETIME(3) |
MongoDB | Timestamp(時間戳記) |
SQLite | NUMERIC |
CockroachDB | TIMESTAMP |
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
NUMERIC
或 STRING
。如果底層資料類型為 STRING
,您必須使用以下格式之一
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 物件。
預設類型對應
連接器 | 預設對應 |
---|---|
PostgreSQL | jsonb |
SQL Server | 不支援 |
MySQL | JSON |
MongoDB | 有效的 BSON 物件(寬鬆模式) |
SQLite | JSONB |
CockroachDB | JSONB |
PostgreSQL
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
json | @db.Json | |
jsonb | @db.JsonB |
MySQL
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
JSON | @db.Json |
MongoDB
Microsoft SQL Server
Microsoft SQL Server 沒有針對 JSON 的特定資料類型。但是,它有一些內建函式可用於讀取和修改 JSON。
SQLite
不支援
CockroachDB
原生資料庫類型 | 原生資料庫類型屬性 | 註解 |
---|---|---|
JSON | JSONB | @db.JsonB |
用戶端
Prisma Client JS |
---|
object(物件) |
Bytes
Bytes
在 2.17.0 及更高版本中可用。
預設類型對應
連接器 | 預設對應 |
---|---|
PostgreSQL | bytea |
SQL Server | varbinary |
MySQL | LONGBLOB |
MongoDB | BinData |
SQLite | BLOB |
CockroachDB | BYTES |
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 |
用戶端
用戶端 | 類型 | 描述 |
---|---|---|
Prisma Client JS | Uint8Array | 請參閱使用 Bytes 的範例 |
Prisma Client JS(v6 之前) | Buffer | 請參閱使用 Bytes 的範例 |
Unsupported
MongoDB 不支援
MongoDB 連接器不支援 Unsupported
類型。
Unsupported
類型在 2.17.0 中引入,讓您可以在 Prisma Schema 中表示 Prisma Client 不支援的資料類型。Unsupported
類型的欄位可以在使用 prisma db pull
進行內省 (Introspection) 期間建立,或手動編寫,並使用 Prisma Migrate 或 db push
在資料庫中建立。
備註
-
具有
Unsupported
類型的欄位在產生的用戶端中不可用。 -
如果模型包含必要的
Unsupported
類型,則prisma.model.create(..)
、prisma.model.update(...)
和prisma.model.upsert(...)
在 Prisma Client 中不可用。 -
當您內省 (introspect) 包含不支援類型的資料庫時,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"))
}
模型
欄位類型修飾符
[]
modifier
使欄位成為列表。
備註
- 不能是可選的(例如
Post[]?
)。
關聯式資料庫
- 僅當您的資料庫原生支援純量列表(陣列)時,資料模型中才支援純量列表。目前,因此僅在使用 PostgreSQL 或 CockroachDB 時才支援純量列表(因為 MySQL 和 SQLite 原生不支援純量列表)。
MongoDB
- 支援純量列表
範例
定義純量列表
- 關聯式資料庫
- MongoDB
model User {
id Int @id @default(autoincrement())
favoriteColors String[]
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
favoriteColors String[]
}
定義具有預設值的純量列表
在 4.0.0 及更高版本中可用。
- 關聯式資料庫
- MongoDB
model User {
id Int @id @default(autoincrement())
favoriteColors String[] @default(["red", "blue", "green"])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
favoriteColors String[] @default(["red", "blue", "green"])
}
?
modifier
使欄位成為可選。
備註
- 不能與列表欄位一起使用(例如
Posts[]
)
範例
可選的 name
欄位
model User {
id Int @id @default(autoincrement())
name String?
}
屬性
屬性修改欄位或區塊(例如 模型)的行為。有兩種方法可以將屬性新增至您的資料模型
- 欄位屬性以
@
為前綴 - 區塊屬性以
@@
為前綴
某些屬性接受引數。屬性中的引數始終被命名,但在大多數情況下,引數名稱可以省略。
注意:簽名中的前導底線表示可以省略引數名稱。
@id
在模型上定義單欄位 ID。
備註
一般
- 不能在關聯欄位上定義
- 不能是可選的
關聯式資料庫
-
對應的資料庫結構:
PRIMARY KEY
-
可以在任何純量欄位上定義(
String
、Int
、enum
)
MongoDB
-
對應的資料庫結構:任何有效的 BSON 類型,陣列除外
-
每個模型都必須定義
@id
欄位 -
底層 ID 欄位名稱始終為
_id
,並且必須使用@map("_id")
進行對應 -
可以在任何純量欄位上定義(
String
、Int
、enum
),除非您想在資料庫中使用ObjectId
-
若要使用
ObjectId
作為您的 ID,您必須 -
支援
cuid()
、uuid()
和ulid()
,但它們不會產生有效的ObjectId
- 對於@id
請改用auto()
-
不支援
autoincrement()
引數
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
map(對應) | 否 | 字串 | 資料庫中底層主鍵約束的名稱。 MySQL 或 MongoDB 不支援。 |
length(長度) | 否 | number | 讓您可以指定要編入索引的值子部分的最大長度。 僅限 MySQL。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
sort(排序) | 否 | 字串 | 讓您可以指定 ID 的條目在資料庫中儲存的順序。可用選項為 Asc 和 Desc 。僅限 SQL Server。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
clustered(叢集) | 否 | 布林值 | 定義 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
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(cuid())
name String
}
model User {
id String @id @default(cuid()) @map("_id")
name String
}
如果您的 id
欄位類型為 ObjectId
,則不能使用 cuid()
產生預設值。請使用以下語法產生有效的 ObjectId
id String @id @default(auto()) @db.ObjectId @map("_id")
產生 uuid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(uuid())
name String
}
model User {
id String @id @default(uuid()) @map("_id")
name String
}
如果您的 id
欄位類型為 ObjectId
,則不能使用 uuid()
產生預設值。請使用以下語法產生有效的 ObjectId
id String @id @default(auto()) @db.ObjectId @map("_id")
產生 ulid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(ulid())
name String
}
model User {
id String @id @default(ulid()) @map("_id")
name String
}
如果您的 id
欄位類型為 ObjectId
,則不能使用 ulid()
產生預設值。請使用以下語法產生有效的 ObjectId
id String @id @default(auto()) @db.ObjectId @map("_id")
沒有預設值的單欄位 ID
在以下範例中,id
沒有預設值
- 關聯式資料庫
- MongoDB
model User {
id String @id
name String
}
model User {
id String @id @map("_id") @db.ObjectId
name String
}
model User {
id String @id @map("_id")
name String
}
請注意,在上述情況下,當使用 Prisma Client 為 User
模型建立新紀錄時,您必須提供自己的 ID 值,例如
const newUser = await prisma.user.create({
data: {
id: 1,
name: "Alice",
},
});
在沒有預設值的關聯純量欄位上指定 ID
在以下範例中,authorId
既是關聯純量,也是 Profile
的 ID
- 關聯式資料庫
- MongoDB
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?
}
model Profile {
authorId String @id @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
bio String
}
model User {
id String @id @map("_id") @db.ObjectId
email String @unique
name String?
profile Profile?
}
在這種情況下,您不能僅建立 Profile
- 您必須使用 Prisma Client 的巢狀寫入建立 User
或將 Profile 連接到現有使用者。
以下範例建立使用者和 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.",
},
},
},
});
以下範例將新的 Profile 連接到使用者
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 - 不能是可選的
- 可以在任何純量欄位上定義(
String
、Int
、enum
) - 不能在關聯欄位上定義
- Prisma Client 中複合 ID 欄位的名稱具有以下模式:
field1_field2_field3
引數
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
fields(欄位) | 是 | FieldReference[] | 欄位名稱列表 - 例如,["firstname", "lastname"] |
name(名稱) | 否 | 字串 | Prisma Client 將為涵蓋所有欄位的引數公開的名稱,例如 fullName 在 fullName: { firstName: "First", lastName: "Last"} 中 |
map(對應) | 否 | 字串 | 資料庫中底層主鍵約束的名稱。 MySQL 不支援。 |
length(長度) | 否 | number | 讓您可以指定要編入索引的值子部分的最大長度。 僅限 MySQL。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
sort(排序) | 否 | 字串 | 讓您可以指定 ID 的條目在資料庫中儲存的順序。可用選項為 Asc 和 Desc 。僅限 SQL Server。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
clustered(叢集) | 否 | 布林值 | 定義 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])
}
當您建立使用者時,必須提供 firstName
和 lastName
的唯一組合
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
紀錄時,您現在必須為 firstName
、lastName
和 isAdmin
提供唯一的數值組合
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 中表示的預設值,在使用內省 (introspection)時,會以
dbgenerated()
函式表示。 - Prisma Schema 中不允許在關聯欄位上設定預設值。但是請注意,您仍然可以在支援關聯的欄位上定義預設值(
@relation
屬性中fields
引數中列出的欄位)。支援關聯的欄位的預設值表示該關聯會自動為您填入。 - 預設值可以與原生支援純量列表的資料庫中的純量列表一起使用。
關聯式資料庫
- 對應的資料庫結構:
DEFAULT
- 預設值可以是靜態值(
4
、"hello"
)或以下函式之一autoincrement()
sequence()
(僅限 CockroachDB)dbgenerated(...)
cuid()
cuid(2)
uuid()
uuid(4)
uuid(7)
ulid()
nanoid()
now()
- 尚無法在 Prisma Schema 中表示的預設值,在使用內省 (introspection)時,會以
dbgenerated(...)
函式表示。 - Prisma Schema 中不允許在關聯欄位上設定預設值。但是請注意,您仍然可以在支援關聯的欄位上定義預設值(
@relation
屬性中fields
引數中列出的欄位)。支援關聯的欄位的預設值表示該關聯會自動為您填入。 - 預設值可以與原生支援純量列表的資料庫中的純量列表一起使用。
- JSON 資料。請注意,JSON 需要用雙引號括在
@default
屬性內,例如:@default("[]")
。如果您想提供 JSON 物件,則需要用雙引號括起來,然後使用反斜線跳脫任何內部的雙引號,例如:@default("{ \"hello\": \"world\" }")
。
MongoDB
- 預設值可以是靜態值(
4
、"hello"
)或以下函式之一
引數
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
value | 是 | 一個運算式 (例如 5 、true 、now() ) | |
map(對應) | 否 | 字串 | 僅限 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
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
profileViews Int @default(0)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
profileViews Int @default(0)
}
Float
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
number Float @default(1.1)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
number Float @default(1.1)
}
Decimal
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
number Decimal @default(22.99)
}
不支援.
BigInt
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
number BigInt @default(34534535435353)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
number BigInt @default(34534535435353)
}
String
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
name String @default("")
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
name String @default("")
}
Boolean
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
isAdmin Boolean @default(false)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
isAdmin Boolean @default(false)
}
DateTime
的預設值
請注意,DateTime
的靜態預設值基於 ISO 8601 標準。
- 關聯式資料庫
- MongoDB
model User {
email String @unique
data DateTime @default("2020-03-19T14:21:00+02:00")
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
data DateTime @default("2020-03-19T14:21:00+02:00")
}
Bytes
的預設值
- 關聯式資料庫
- MongoDB
model User {
email String @unique
secret Bytes @default("SGVsbG8gd29ybGQ=")
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
secret Bytes @default("SGVsbG8gd29ybGQ=")
}
enum
的預設值
- 關聯式資料庫
- MongoDB
enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
role Role @default(USER)
posts Post[]
profile Profile?
}
enum Role {
USER
ADMIN
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
role Role @default(USER)
posts Post[]
profile Profile?
}
純量列表的預設值
- 關聯式資料庫
- MongoDB
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
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
posts Post[]
favoriteColors String[] @default(["red", "yellow", "purple"])
roles Role[] @default([USER, DEVELOPER])
}
enum Role {
USER
DEVELOPER
ADMIN
}
@unique
為此欄位定義唯一約束。
備註
一般
- 標註
@unique
的欄位可以是選填或必填的 - 如果標註
@unique
的欄位代表模型上唯一的唯一約束,且模型沒有@id
/@@id
,則該欄位必須為必填 - 一個模型可以有任意數量的唯一約束
- 可以定義在任何純量欄位上
- 無法定義在關聯欄位上
關聯式資料庫
- 對應的資料庫結構:
UNIQUE
NULL
值被視為相異 (允許在同一欄位中有多個包含NULL
值的列)- 新增唯一約束會自動為指定的欄位新增對應的唯一索引。
MongoDB
- 由 MongoDB 中的 唯一索引 強制執行
引數
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
map(對應) | 否 | 字串 | |
length(長度) | 否 | number | 讓您可以指定要編入索引的值子部分的最大長度。 僅限 MySQL。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
sort(排序) | 否 | 字串 | 允許您指定約束的條目在資料庫中儲存的順序。可用的選項為 Asc 和 Desc 。在 3.5.0 及更新版本中為預覽功能,在 4.0.0 及更新版本中為正式發佈功能。 |
clustered(叢集) | 否 | 布林值 | 定義約束是否為叢集或非叢集。預設為 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
欄位上指定唯一屬性
- 關聯式資料庫
- MongoDB
model User {
email String @unique
name String
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
name String
}
在選填 String
欄位上指定唯一屬性
- 關聯式資料庫
- MongoDB
model User {
id Int @id @default(autoincrement())
email String? @unique
name String
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String? @unique
name String
}
在關聯純量欄位 authorId
上指定唯一屬性
- 關聯式資料庫
- MongoDB
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[]
}
model Post {
author User @relation(fields: [authorId], references: [id])
authorId String @unique @db.ObjectId
title String
published Boolean @default(false)
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String? @unique
name String
Post Post[]
}
使用 cuid()
值作為預設值來指定唯一屬性
- 關聯式資料庫
- MongoDB
model User {
token String @unique @default(cuid())
name String
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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
欄位
引數
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
fields(欄位) | 是 | FieldReference[] | 欄位名稱列表 - 例如,["firstname", "lastname"] 。欄位必須為必填 - 請參閱備註。 |
name(名稱) | 否 | 字串 | 欄位唯一組合的名稱 - 預設為 fieldName1_fieldName2_fieldName3 |
map(對應) | 否 | 字串 | |
length(長度) | 否 | number | 讓您可以指定要編入索引的值子部分的最大長度。 僅限 MySQL。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
sort(排序) | 否 | 字串 | 允許您指定約束的條目在資料庫中儲存的順序。可用的選項為 Asc 和 Desc 。在 3.5.0 及更新版本中為預覽功能,在 4.0.0 及更新版本中為正式發佈功能。 |
clustered(叢集) | 否 | 布林值 | 定義約束是否為叢集或非叢集。預設為 false 。僅限 SQL Server。在 3.13.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
在 @@unique
屬性中,fields
引數的名稱可以省略
@@unique(fields: [title, author])
@@unique([title, author])
@@unique(fields: [title, author], name: "titleAuthor")
length
和 sort
引數會新增至相關的欄位名稱
@@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
欄位上指定多欄位唯一屬性
- 關聯式資料庫
- MongoDB
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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
欄位上指定多欄位唯一屬性
- 關聯式資料庫
- MongoDB
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName, isAdmin])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName, isAdmin])
}
指定包含關聯欄位的多欄位唯一屬性
- 關聯式資料庫
- MongoDB
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[]
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
title String
published Boolean @default(false)
@@unique([authorId, title])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
posts Post[]
}
為多欄位唯一屬性指定自訂 name
- 關聯式資料庫
- MongoDB
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique(fields: [firstName, lastName, isAdmin], name: "admin_identifier")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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
同時建立索引
- 將索引欄位定義為運算式 (例如
- PostgreSQL 和 CockroachDB
雖然您無法在 Prisma Schema 中設定這些選項,但您仍然可以直接在資料庫層級設定它們。
MongoDB
引數
名稱 | 是否必填 | 類型 | 描述 |
---|---|---|---|
fields(欄位) | 是 | FieldReference[] | 欄位名稱列表 - 例如,["firstname", "lastname"] |
name(名稱) | 否 | 字串 | Prisma Client 將為涵蓋所有欄位的引數公開的名稱,例如 fullName 在 fullName: { firstName: "First", lastName: "Last"} 中 |
map(對應) | 否 | map(對應) | 基礎資料庫中索引的名稱 (如果您未指定名稱,Prisma 會產生一個符合識別碼長度限制的索引名稱。Prisma 使用以下命名慣例:tablename.field1_field2_field3_unique ) |
length(長度) | 否 | number | 讓您可以指定要編入索引的值子部分的最大長度。 僅限 MySQL。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
sort(排序) | 否 | 字串 | 允許您指定索引或約束的條目在資料庫中儲存的順序。可用的選項為 asc 和 desc 。在 3.5.0 及更新版本中為預覽功能,在 4.0.0 及更新版本中為正式發佈功能。 |
clustered(叢集) | 否 | 布林值 | 定義索引是否為叢集或非叢集。預設為 false 。僅限 SQL Server。在 3.5.0 及更高版本中處於預覽狀態,在 4.0.0 及更高版本中正式發佈。 |
type | 否 | identifier | 允許您指定索引存取方法。預設為 BTree 。僅限 PostgreSQL 和 CockroachDB。在 3.6.0 及更新版本中使用 Hash 索引存取方法為預覽功能,在 3.14.0 中新增了 Gist 、Gin 、SpGist 和 Brin 方法。在 4.0.0 及更新版本中為正式發佈功能。 |
ops | 否 | identifier 或 function | 允許您為某些索引類型定義索引運算子。 僅限 PostgreSQL。在 3.14.0 及更新版本中為預覽功能,在 4.0.0 及更新版本中為正式發佈功能。 |
在 @@index
屬性中,name 為 fields
引數的名稱可以省略
@@index(fields: [title, author])
@@index([title, author])
length
和 sort
引數會新增至相關的欄位名稱
@@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
屬性
引數
名稱 | 類型 | 是否必填 | 描述 | 範例 |
---|---|---|---|---|
name(名稱) | 字串 | 有時 (例如為了消除關聯的歧義) | 定義關聯的名稱。在 m-n 關聯中,它也決定了基礎關聯表的名稱。 | "CategoryOnPost" 、"MyRelation" |
fields(欄位) | FieldReference[] | 在標註的關聯欄位上 | 目前模型的欄位列表 | ["authorId"] 、["authorFirstName, authorLastName"] |
references | FieldReference[] | 在標註的關聯欄位上 | 關聯另一端模型的欄位列表 | ["id"] 、["firstName, lastName"] |
map(對應) | 字串 | 否 | 為資料庫中的外鍵定義自訂名稱。 | ["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。
備註
一般
@map
不會重新命名資料庫中的欄位@map
會 變更產生用戶端中的欄位名稱
MongoDB
您的 @id
欄位必須包含 @map("_id")
。例如
model User {
id String @default(auto()) @map("_id") @db.ObjectId
}
引數
名稱 | 類型 | 是否必填 | 描述 | 範例 |
---|---|---|---|---|
name(名稱) | 字串 | 是 | 資料庫欄位 (關聯式資料庫) 或文件欄位 (MongoDB) 名稱。 | "comments" 、"someFieldName" |
在 @map
屬性中,name
引數的名稱可以省略
@map(name: "is_admin")
@map("users")
簽名
@map(_ name: String)
範例
將 firstName
欄位對應到名為 first_name
的欄位
- 關聯式資料庫
- MongoDB
model User {
id Int @id @default(autoincrement())
firstName String @map("first_name")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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。
引數
名稱 | 類型 | 是否必填 | 描述 | 範例 |
---|---|---|---|---|
name(名稱) | 字串 | 是 | 資料庫表 (關聯式資料庫) 或集合 (MongoDB) 名稱。 | "comments" 、"someTableOrCollectionName" |
在 @@map
屬性中,name
引數的名稱可以省略
@@map(name: "users")
@@map("users")
簽名
@@map(_ name: String)
範例
將 User
模型對應到名為 users
的資料庫表/集合
- 關聯式資料庫
- MongoDB
model User {
id Int @id @default(autoincrement())
name String
@@map("users")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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 層級實作
如果您同時使用 now()
,則時間可能與 @updatedAt
值不同,如果您的資料庫和應用程式具有不同的時區。發生這種情況是因為 @updatedAt
在 Prisma ORM 層級運作,而 now()
在資料庫層級運作。
如果您傳遞空的更新子句,@updatedAt
值將保持不變。例如
await prisma.user.update({
where: {
id: 1,
},
data: {}, //<- Empty update clause
});
引數
不適用
簽名
@updatedAt
範例
- 關聯式資料庫
- MongoDB
model Post {
id String @id
updatedAt DateTime @updatedAt
}
model Post {
id String @id @map("_id") @db.ObjectId
updatedAt DateTime @updatedAt
}
@ignore
將 @ignore
新增到您想要從 Prisma Client 中排除的欄位 (例如,您不希望 Prisma Client 使用者更新的欄位)。忽略的欄位會從產生的 Prisma Client 中排除。當對沒有 @default
的必填欄位執行此操作時,模型的 create
方法會停用 (因為資料庫無法在沒有該資料的情況下建立條目)。
備註
- 在 2.17.0 及更新版本中,當您進行內省時,Prisma ORM 會自動將
@ignore
新增到參照無效模型的欄位。
範例
以下範例示範手動新增 @ignore
以從 Prisma Client 中排除 email
欄位
model User {
id Int @id
name String
email String @ignore // this field will be excluded
}
@@ignore
將 @@ignore
新增到您想要從 Prisma Client 中排除的模型 (例如,您不希望 Prisma 使用者更新的模型)。忽略的模型會從產生的 Prisma Client 中排除。
備註
範例
在以下範例中,Post
模型無效,因為它沒有唯一識別符。使用 @@ignore
將其從產生的 Prisma Client API 中排除
/// 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 中排除
/// 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
預覽功能。多個資料庫 Schema 支援目前可用於 PostgreSQL、CockroachDB 和 SQL Server 連接器。
將 @@schema
新增到模型,以指定資料庫中的哪個 Schema 應包含與該模型相關聯的表。
引數
名稱 | 類型 | 是否必填 | 描述 | 範例 |
---|---|---|---|---|
name(名稱) | 字串 | 是 | 資料庫 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
功能的更多資訊,請參閱本指南。
屬性函數
auto()
表示由資料庫自動產生的預設值。
備註
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 值。
備註
-
與大多數資料庫上的
Int
相容 (CockroachDB 上為BigInt
) -
在資料庫層級實作,表示它會顯現在資料庫結構描述中,並且可以透過內省機制識別。資料庫實作
資料庫 實作 PostgreSQL SERIAL
類型MySQL AUTO_INCREMENT
屬性SQLite AUTOINCREMENT
關鍵字CockroachDB SERIAL
類型
範例
產生自動遞增整數作為 ID (僅限關聯式資料庫)
model User {
id Int @id @default(autoincrement())
name String
}
sequence()
僅 CockroachDB 支援
序列函數僅 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 實作,因此在底層資料庫結構描述中「不可見」。當使用 內省機制 時,您仍然可以使用
cuid()
,方法是手動變更您的 Prisma 結構描述 和 產生 Prisma Client,在這種情況下,值將由 Prisma 的 查詢引擎 產生。 - 由於
cuid()
輸出的長度根據 cuid 建立者的說法是未定義的,因此為了允許容納非常大的值,安全的欄位大小為 30 個字元。如果您將欄位大小設定為小於 30,然後cuid()
產生了更大的值,您可能會看到 Prisma Client 錯誤,例如Error: The provided value for the column is too long for the column's type.
- 對於 MongoDB:
cuid()
不會產生有效的ObjectId
。如果您想在底層資料庫中使用ObjectId
,可以使用@db.ObjectId
語法。但是,如果您的_id
欄位類型不是ObjectId
,您仍然可以使用cuid()
。
範例
產生 cuid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(cuid())
name String
}
model User {
id String @id @default(cuid()) @map("_id")
name String
}
根據 cuid2
規範產生 cuid(2)
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(cuid(2))
name String
}
model User {
id String @id @default(cuid(2)) @map("_id")
name String
}
uuid()
根據 UUID 規範產生全域唯一識別碼。Prisma ORM 支援版本 4 (預設) 和 7。
備註
- 與
String
相容。 - 由 Prisma ORM 實作,因此在底層資料庫結構描述中「不可見」。當使用 內省機制 時,您仍然可以使用
uuid()
,方法是手動變更您的 Prisma 結構描述 和 產生 Prisma Client,在這種情況下,值將由 Prisma ORM 的 查詢引擎 產生。 - 對於關聯式資料庫:如果您不想使用 Prisma ORM 的
uuid()
函數,您可以使用 具有dbgenerated
的原生資料庫函數。 - 對於 MongoDB:
uuid()
不會產生有效的ObjectId
。如果您想在底層資料庫中使用ObjectId
,可以使用@db.ObjectId
語法。但是,如果您的_id
欄位類型不是ObjectId
,您仍然可以使用uuid()
。
範例
使用 UUID v4 產生 uuid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(uuid())
name String
}
model User {
id String @id @default(uuid()) @map("_id")
name String
}
使用 UUID v7 產生 uuid(7)
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(uuid(7))
name String
}
model User {
id String @id @default(uuid(7)) @map("_id")
name String
}
ulid()
根據 ULID 規範產生全域唯一且按詞彙順序可排序的識別碼。
備註
ulid()
將產生 128 位元的隨機識別碼,表示為 26 個字元的英數字元字串,例如:01ARZ3NDEKTSV4RRFFQ69G5FAV
範例
產生 ulid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(ulid())
name String
}
model User {
id String @id @default(ulid()) @map("_id")
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 實作,因此在底層資料庫結構描述中「不可見」。當使用 內省機制 時,您仍然可以使用
uuid()
,方法是手動變更您的 Prisma 結構描述 和 產生 Prisma Client,在這種情況下,值將由 Prisma ORM 的 查詢引擎 產生。 - 對於 MongoDB:
nanoid()
不會產生有效的ObjectId
。如果您想在底層資料庫中使用ObjectId
,可以使用@db.ObjectId
語法。但是,如果您的_id
欄位類型不是ObjectId
,您仍然可以使用nanoid()
。
範例
產生具有 21 個字元的 nanoid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(nanoid())
name String
}
model User {
id String @id @default(nanoid()) @map("_id")
name String
}
產生具有 16 個字元的 nanoid()
值作為 ID
- 關聯式資料庫
- MongoDB
model User {
id String @id @default(nanoid(16))
name String
}
model User {
id String @id @default(nanoid(16)) @map("_id")
name String
}
now()
設定建立記錄時的時間戳記。
備註
一般
- 與
DateTime
相容
如果您同時使用 @updatedAt
,則時間可能與 now()
值不同,如果您的資料庫和應用程式具有不同的時區。發生這種情況是因為 @updatedAt
在 Prisma ORM 層級運作,而 now()
在資料庫層級運作。
關聯式資料庫
-
在資料庫層級實作,表示它會顯現在資料庫結構描述中,並且可以透過內省機制識別。資料庫實作
資料庫 實作 PostgreSQL CURRENT_TIMESTAMP
和別名,例如now()
MySQL CURRENT_TIMESTAMP
和別名,例如now()
SQLite CURRENT_TIMESTAMP
和別名,例如date('now')
CockroachDB CURRENT_TIMESTAMP
和別名,例如now()
MongoDB
- 在 Prisma ORM 層級實作
範例
設定建立記錄時的目前時間戳記值
- 關聯式資料庫
- MongoDB
model User {
id String @id
createdAt DateTime @default(now())
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
}
dbgenerated(...)
表示無法在 Prisma 結構描述中表達的預設值 (例如 random()
)。
備註
關聯式資料庫
-
與任何純量類型相容
-
在 2.21.0 和更高版本中,不能是空字串
dbgenerated("")
-
在 2.17.0 和更高版本中接受
String
值,這讓您可以 -
dbgenerated(...)
中的字串值可能與資料庫傳回的預設值不符,因為字串等值可能會被明確轉換 (例如'hello'::STRING
)。當存在不符時,Prisma Migrate 會指示仍需要遷移。您可以使用prisma db pull
來推斷正確的值以解決差異。(相關問題)
範例
為 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 結構描述中宣告 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
類型。
定義 列舉。
備註
- 列舉型別受到 PostgreSQL 和 MySQL 原生支援
- 列舉型別在 SQLite 和 MongoDB 中於 Prisma ORM 層級實作和強制執行
命名慣例
- 列舉名稱必須以字母開頭 (它們通常以 PascalCase 拼寫)
- 列舉必須使用單數形式 (例如
Role
而不是role
、roles
或Roles
)。 - 必須遵循以下正規表示式:
[A-Za-z][A-Za-z0-9_]*
範例
指定具有兩個可能值的 enum
- 關聯式資料庫
- MongoDB
enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
role Role
}
enum Role {
USER
ADMIN
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
role Role
}
指定具有兩個可能值的 enum
並設定預設值
- 關聯式資料庫
- MongoDB
enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
role Role @default(USER)
}
enum Role {
USER
ADMIN
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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
}