TL;DR
Prisma ORM のスキーマファイルから自動生成される、型安全なクエリビルダ。
仕組み
@prisma/client をインストールすると、prisma generate も実行されてクライアントが生成される。事前に prisma migrate dev を実行していれば、そのときにも自動で生成されている。
$ npm i @prisma/client生成されたクライアントは、モデルごとに次のようなメソッドを持つ。
findUnique: ID やユニークな属性で、レコードを 1 件取得するfindMany: レコードを複数件取得するcreate: レコードを 1 件作成するupdate: レコードを 1 件更新するdelete: レコードを 1 件削除する
例
次のスキーマの User から、リレーション先の profile も含めて取得する。リレーション先のフィールドを選ぶには、select をネストする。
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
profileId String?
profile Profile?
accounts Account[]
sessions Session[]
}const users = await prisma.user.findMany({
select: {
id: true,
name: true,
image: true,
profile: { select: { screenName: true } },
},
})作成、更新、削除は次のように書く。
await prisma.task.create({
data: { name, dueDate, description },
})
await prisma.task.update({
data: { name, dueDate, status, description },
where: { id },
})
await prisma.task.delete({ where: { id } })注意点
findUnique は、レコードが存在しないとき null を返す。例外(NotFoundError)を投げたいときは、findUniqueOrThrow を使う。
Next.js で Prisma Client の呼び出しをメモ化するには、React.cache を使う。
関連
出典
- Prisma Client API reference - findUnique
- Prisma Client API reference - findUniqueOrThrow
- Prisma Client API reference - findMany
- Prisma Client API reference - create
- Prisma Client API reference - update
- Prisma Client API reference - delete
- Relation queries - Select specific fields of included relations