跳至主要內容

欄位與類型

本節介紹您可以在 Prisma Client 中使用的各種特殊欄位與類型。

使用 Decimal

Decimal 欄位由 Decimal.js 函式庫 代表。以下範例示範如何匯入並使用 Prisma.Decimal

import { PrismaClient, Prisma } from '@prisma/client'

const newTypes = await prisma.sample.create({
data: {
cost: new Prisma.Decimal(24.454545),
},
})

您也可以進行算術運算。

import { PrismaClient, Prisma } from '@prisma/client'

const newTypes = await prisma.sample.create({
data: {
cost: new Prisma.Decimal(24.454545).plus(1),
},
})

Prisma.Decimal 使用 Decimal.js,請參閱 Decimal.js 文件 以了解更多資訊。

警告

目前 Decimal 欄位 尚未在 MongoDB 中得到支援

使用 BigInt

總覽

BigInt 欄位由 BigInt 類型(需要 Node.js 10.4.0+)代表。以下範例示範如何使用 BigInt 類型。

import { PrismaClient, Prisma } from '@prisma/client'

const newTypes = await prisma.sample.create({
data: {
revenue: BigInt(534543543534),
},
})

序列化 BigInt

Prisma Client 將記錄回傳為一般的 JavaScript 物件。如果您嘗試在包含 BigInt 欄位的物件上使用 JSON.stringify,將會看到以下錯誤。

Do not know how to serialize a BigInt

要解決此問題,請使用 JSON.stringify 的自訂實作。

JSON.stringify(
this,
(key, value) => (typeof value === 'bigint' ? value.toString() : value) // return everything else unchanged
)

使用 Bytes

Bytes 欄位由 Uint8Array 類型代表。以下範例示範如何使用 Uint8Array 類型。

import { PrismaClient, Prisma } from '@prisma/client'

const newTypes = await prisma.sample.create({
data: {
myField: new Uint8Array([1, 2, 3, 4]),
},
})

請注意,在 Prisma v6 之前Bytes 是由 Buffer 類型代表。

import { PrismaClient, Prisma } from '@prisma/client'

const newTypes = await prisma.sample.create({
data: {
myField: Buffer.from([1, 2, 3, 4]),
},
})

詳情請參閱 v6 升級指南

使用 DateTime

注意

目前存在一個 錯誤,導致無法將 DateTime 值作為字串傳入,否則會產生執行時期錯誤。DateTime 值必須作為 Date 物件傳入(即使用 new Date('2024-12-04') 而非 '2024-12-04')。

在建立具有 DateTime 類型欄位的記錄時,Prisma Client 接受符合 ISO 8601 標準的 Date 物件作為值。

考慮以下 schema:

model User {
id Int @id @default(autoincrement())
birthDate DateTime?
}

以下是一些建立新記錄的範例:

1998 年 1 月 1 日;00 時 00 分 000 毫秒
await prisma.user.create({
data: {
birthDate: new Date('1998')
}
})
1998 年 12 月 1 日;00 時 00 分 000 毫秒
await prisma.user.create({
data: {
birthDate: new Date('1998-12')
}
})
1998 年 12 月 24 日;00 時 00 分 000 毫秒
await prisma.user.create({
data: {
birthDate: new Date('1998-12-24')
}
})
1998 年 12 月 24 日;06 時 22 分 33 秒 444 毫秒
await prisma.user.create({
data: {
birthDate: new Date('1998-12-24T06:22:33.444Z')
}
})

使用 Json

參閱:使用 Json 欄位

使用純量列表 / 純量陣列

參閱:使用純量列表 / 陣列

使用複合 ID 與複合唯一約束

參閱:使用複合 ID 與複合唯一約束

© . This site is unofficial and not affiliated with Prisma Data, Inc.