跳到主要内容

字段与类型

本节涵盖了你可以与 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 和复合唯一约束

© . All rights reserved.