The Complete Guide to Mastering Prisma ORM with Claude Code
A comprehensive guide to mastering prisma orm using Claude Code with practical examples and best practices.
Prisma ORM とは
Prisma ORMはTypeScriptのための次世代ORMです。型安全なデータベースアクセス、直感的なスキーマ定義、自動マイグレーションを提供します。Claude Codeと組み合わせれば、データベース設計から実装まで効率的に進められます。
スキーマ設計
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
name String
avatar String?
posts Post[]
comments Comment[]
profile Profile?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([email])
}
model Profile {
id String @id @default(cuid())
bio String?
url String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId String @unique
}
model Post {
id String @id @default(cuid())
title String
content String
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId String
categories Category[]
comments Comment[]
publishedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([authorId])
@@index([published, publishedAt])
}
model Category {
id String @id @default(cuid())
name String @unique
slug String @unique
posts Post[]
}
model Comment {
id String @id @default(cuid())
content String
author User @relation(fields: [authorId], references: [id])
authorId String
post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
postId String
createdAt DateTime @default(now())
@@index([postId])
}
CRUD操作
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
// 作成
async function createPost(data: {
title: string;
content: string;
authorId: string;
categoryIds: string[];
}) {
return prisma.post.create({
data: {
title: data.title,
content: data.content,
author: { connect: { id: data.authorId } },
categories: {
connect: data.categoryIds.map((id) => ({ id })),
},
},
include: {
author: { select: { id: true, name: true } },
categories: true,
},
});
}
// 検索(ページネーション付き)
async function getPosts(params: {
page?: number;
perPage?: number;
category?: string;
search?: string;
}) {
const { page = 1, perPage = 20, category, search } = params;
const where = {
published: true,
...(category && {
categories: { some: { slug: category } },
}),
...(search && {
OR: [
{ title: { contains: search, mode: "insensitive" as const } },
{ content: { contains: search, mode: "insensitive" as const } },
],
}),
};
const [posts, total] = await Promise.all([
prisma.post.findMany({
where,
skip: (page - 1) * perPage,
take: perPage,
orderBy: { publishedAt: "desc" },
include: {
author: { select: { id: true, name: true, avatar: true } },
categories: true,
_count: { select: { comments: true } },
},
}),
prisma.post.count({ where }),
]);
return {
posts,
pagination: {
total,
page,
perPage,
totalPages: Math.ceil(total / perPage),
},
};
}
トランザクション
async function publishPost(postId: string) {
return prisma.$transaction(async (tx) => {
const post = await tx.post.findUnique({
where: { id: postId },
});
if (!post) throw new Error("Post not found");
if (post.published) throw new Error("Already published");
const updated = await tx.post.update({
where: { id: postId },
data: {
published: true,
publishedAt: new Date(),
},
});
// 通知を作成
await tx.notification.create({
data: {
type: "POST_PUBLISHED",
message: `「${post.title}」が公開されました`,
userId: post.authorId,
},
});
return updated;
});
}
マイグレーション
# スキーマ変更後のマイグレーション
npx prisma migrate dev --name add_profile_table
# 本番環境へのデプロイ
npx prisma migrate deploy
# スキーマの同期(開発用)
npx prisma db push
Einsatz mit Claude Codeプロンプト
Prismaを使った開発をClaude Codeに依頼する例です。基本的な使い方はClaude Code入門ガイド、他のORMとの比較はDrizzle ORM活用法も参照してください。
Prismaでブログのデータベーススキーマを設計して。
- ユーザー、記事、カテゴリ、コメントのモデル
- 適切なリレーションとインデックス
- ページネーション付きの検索クエリ
- トランザクションを使った公開処理
- マイグレーションファイルも生成して
Prismaの詳細はPrisma公式ドキュメントを参照してください。Claude Codeの活用法は公式ドキュメントで確認できます。
Zusammenfassung
Prisma ORMは型安全なデータベースアクセスを提供し、開発体験を大幅に向上させます。Claude Codeにスキーマ設計からクエリ最適化まで依頼すれば、堅牢なデータ層を効率的に構築できます。
Related Posts
Claude Code für Nicht-Entwickler: KI-gestützte Entwicklung ohne Programmierkenntnisse
Erfahren Sie, wie Sie Claude Code ohne Programmiererfahrung nutzen können. Von grundlegenden Terminal-Befehlen bis zur Website-Erstellung – dieser einsteigerfreundliche Leitfaden erklärt alles Schritt für Schritt.
Was ist Claude Code? Der komplette Leitfaden von der Installation bis zur ersten Nutzung
Ein einsteigerfreundlicher Leitfaden zur Installation und Nutzung von Claude Code. Erfahren Sie, wie Sie noch heute mit diesem terminalbasierten KI-Coding-Assistenten loslegen.
Claude Code Preispläne und wie Sie den ROI einschätzen
Eine klare Aufschlüsselung der Preisstruktur von Claude Code. Vergleichen Sie Pläne, lernen Sie Kostenoptimierungsstrategien und verstehen Sie den realen ROI mit konkreten Zahlen.