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です。类型安全な数据库アクセス、直感的なSchema定義、自動迁移を提供します。与 Claude Code組み合わせれば、数据库设计から实现まで高效地進められます。

Schema设计

// 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 CodeSchema设计から查询优化まで依頼すれば、堅牢な数据層を高效地构建可以。

#Claude Code #Prisma #ORM #database #TypeScript