欄位 & 類型
本節涵蓋您可以在 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
類型欄位的記錄時,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 日;22 時 33 分 444 毫秒
await prisma.user.create({
data: {
birthDate: new Date('1998-12-24T06:22:33.444Z')
}
})
使用 Json
請參閱:使用 Json
欄位
使用純量列表 / 純量陣列
請參閱:使用純量列表 / 陣列
使用複合 ID 和複合唯一約束
請參閱:使用複合 ID 和複合唯一約束