跳到主要內容

欄位與型別

本節涵蓋了你可以與 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 之前BytesBuffer 型別表示

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.