Getting Started

The 완전 가이드 to Mastering Prisma ORM: Claude Code 활용 가이드

A comprehensive guide to mastering prisma orm: 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

Claude Code로の활용プロンプト

Prisma를 사용한개발をClaude Code에依頼する例です。기본적인使い方はClaude Code入門가이드、他のORMとの比較はDrizzle ORM활용法도 참고하세요.

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

Prisma의 상세 정보는Prisma공식 문서를 참고하세요.Claude Code의 활용법은공식 문서에서 확인할 수 있습니다.

정리

Prisma ORMは타입安全な데이터베이스アクセスを提供し、개발体験を大幅に向上させます。Claude Code에스키마설계から쿼리최적화まで依頼すれば、堅牢な데이터層を효율적으로구축할 수 있습니다。

#Claude Code #Prisma #ORM #database #TypeScript