1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Prismaでリレーション(include)先の型をまとめて取得する

Last updated at Posted at 2024-12-17

こんにちは。粘着系エンジニアのbamboo-houseです。
リレーション先の型について、とある方法を使うと自分で定義することなく型を取得することができるので参考にしてみてください!

schema.prisma(モデル定義)

model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int
}

リレーション先の型を取得する

prisma generateした後に、

type UserWithPost = Prisma.UserGetPayload<{
    include: {
        posts: true;
    };
}>;
// {
//   posts: {
//     id: number;
//     authorId: number;
//   }[]
// } & {
//   id: number;
// }

// selectで絞り込むこともできます
type UserWithPost = Prisma.UserGetPayload<{
    select: {
        id: true;
        posts: {
            id: true;
        };
    };
}>;
// {
//   id: number;
//   posts: {
//     id: number;
//   }[];
// }
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?