Prisma応用ガイド
1. 複数テーブルのリレーション設計
例:UserとPost(ユーザーは複数の記事を持つ)
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
userId Int
user User @relation(fields: [userId], references: [id])
}
2. リレーションのクエリ操作
- データ登録
await prisma.user.create({
data: {
name: '田中一郎',
posts: {
create: [
{ title: '記事1', content: '内容1' },
{ title: '記事2', content: '内容2' },
],
},
},
});
- データ取得(リレーション込み)
const users = await prisma.user.findMany({
include: { posts: true },
});
3. パフォーマンス最適化:selectとincludeの違い
-
select
→ 必要なフィールドだけ取りたい -
include
→ リレーションも含めたい
例:
const user = await prisma.user.findUnique({
where: { id: 1 },
select: { name: true },
});
4. バルク操作(createMany, updateMany)
大量データ登録・更新も簡単
await prisma.post.createMany({
data: [
{ title: 'まとめ記事1', content: '概要1', userId: 1 },
{ title: 'まとめ記事2', content: '概要2', userId: 1 },
],
});
5. 複雑なフィルタリング
例:特定ユーザーの記事だけ取得
const posts = await prisma.post.findMany({
where: {
user: {
name: {
contains: '田中',
},
},
},
});
6. Prismaのベストプラクティス
-
prisma.$disconnect()
を忘れず使う(DB接続解放) - モデル名は単数形推奨(User, Post)
- エラーハンドリングを入れる
- 必要ならPrisma Middleware(ロギングなど)
Prismaマイグレーションの仕組み
- Prismaのモデルを変更する
-
npx prisma migrate dev --name xxx
でマイグレーション - マイグレーション履歴がコードとして残る
実際にできるもの
-
prisma/migrations/{タイムスタンプ名}/migration.sql
- 中身は純粋なSQL!
- 手動編集も可能(ただし上級者向け)
マイグレーションの流れまとめ
schema.prismaを編集
↓
migrate devでSQLファイル作成+適用
↓
DBに反映
↓
履歴もGit管理できる
本番環境への適用
開発と本番では違うコマンドを使う
npx prisma migrate deploy
→ これはすでに作ったマイグレーションSQLだけを本番DBに適用するコマンド!
パフォーマンス最適化Tips
- 必要なフィールドだけ取得する(
select
を使う) - 可能なら
createMany
やupdateMany
で一括処理する - Prisma Clientをアプリ内で使いまわしてコネクション数を抑える