フィールドと型
このセクションでは、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
オブジェクトとして値を受け入れます。
以下のスキーマを考慮してください
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と複合ユニーク制約の操作