跳到主内容

字段与类型

本节介绍您可以在 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 文档 以了解更多信息。

警告

目前 在 MongoDB 中尚不支持 使用 Decimal 字段。

使用 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

注意

当前存在一个bug,该 bug 不允许您将 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 年 01 月 01 日;00 时 00 分 000 毫秒
await prisma.user.create({
data: {
birthDate: new Date('1998')
}
})
1998 年 12 月 01 日;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 和复合唯一约束