Prismaでリレーション付きの型を取得する

このようなテーブルを作ったとき、特定のユーザーと一緒にリレーション先のPostのデータもほしいときがよくあります。

model User {
  id    String @id @default(auto()) @map("_id") @db.ObjectId
  posts Post[]
}

model Post {
  id       String @id @default(auto()) @map("_id") @db.ObjectId
  author   User   @relation(fields: [authorId], references: [id])
  authorId String @db.ObjectId // relation scalar field  (used in the `@relation` attribute above)
}

Prismaのクエリにはデフォルトでリレーションが含まれていないので、prisma generateで生成される型にもリレーションは含まれません。

そのため、このように型を定義する必要があると思われますが、型を作る必要はありません。

type UserWithPosts = {
  id: string
  email: string
  name: string | null
  posts: Post[]
}

Prisma.UserGetPayloadユーティリティ関数を使用して、すべてのユーザーとその投稿を返すのに使用できるタイプを作成します。

こうすることでリレーション付きのユーザーの型を取得する

import type { Prisma } from "@prisma/client";
type Props = {
  user: Prisma.UserGetPayload<{
    include: {
      Post: true;
    };
  }>;
};
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする


The reCAPTCHA verification period has expired. Please reload the page.

目次