MENU

primsma 1対多 多対多のケース

目的

PrismaによるDB定義と、呼び出しの方法を 1対多、多対多で調べてみた

1対多

  • 定義
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])
}
  • 呼び出し
  const user = await prisma.user.findUnique({
      where: { id: parseInt(userId) },
      include: {
        posts: true,
      },
    });

多対多

  • テーブル定義
model User {
  id    Int      @id @default(autoincrement())
  name  String
  posts Post[]   @relation("UserToPost", references: [id])
}

model Post {
  id      Int      @id @default(autoincrement())
  title   String
  content String
  users   User[]   @relation("UserToPost", references: [id])
}

model UserToPost {
  id      Int      @id @default(autoincrement())
  userId  Int
  postId  Int
  user    User     @relation(fields: [userId], references: [id])
  post    Post     @relation(fields: [postId], references: [id])
  @@unique([userId, postId]) 
}
  • 呼び出し
    const user = await prisma.user.findUnique({
      where: { id: parseInt(userId) },
      include: {
        posts: true,
      },
    });
  • ユーザーがポストする場合の処理

中間テーブルを作成する方法は2つあるらしい

### パターン1

    // 1. ポストを作成
    const post = await prisma.post.create({
      data: {
        title,
        content,
      },
    });

    // 2. ポストとユーザーを関連付ける
    await prisma.userToPost.create({
      data: {
        userId: parseInt(userId),
        postId: post.id, // 新しく作成したポストのIDを使用
      },
    });

### パターン2
await prisma.user.update({
  where: { id: parseInt(userId) },
  data: {
    posts: {
      connect: { id: parseInt(postId) }, // 既存のポストを関連付ける
    },
  },
});