Getting Started

Prisma ORM avec Claude Code

Découvrez prisma ORM avec Claude Code. Conseils pratiques et exemples de code inclus.

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

Claude Codeでの活用プロンプト

Prismaを使った開発をClaude Codeに依頼する例です。基本的な使い方はClaude Code入門ガイド、他のORMとの比較はDrizzle ORM活用法も参照してください。

Prismaでブログのデータベーススキーマを設計して。
- ユーザー、記事、カテゴリ、コメントのモデル
- 適切なリレーションとインデックス
- ページネーション付きの検索クエリ
- トランザクションを使った公開処理
- マイグレーションファイルも生成して

Prismaの詳細はPrisma公式ドキュメントを参照してください。Claude Codeの活用法は公式ドキュメントで確認できます。

Summary

Prisma ORMは型安全なデータベースアクセスを提供し、開発体験を大幅に向上させます。Claude Codeにスキーマ設計からクエリ最適化まで依頼すれば、堅牢なデータ層を効率的に構築できます。

#Claude Code #Prisma #ORM #database #TypeScript