Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
4 replies
jix74

Complicated recursive types for self-relations in prisma models...

Prisma documentation says that types only contain the model's scalar fields, but doesn't account for any relations, thus you must use GetPayload.

Prisma Model:
model Category {
  id String @id @default(cuid())
  name        String?          @unique
  parent    Category?  @relation("CategoryToCategory", fields: [parentId], references: [id])
  parentId  String?
  children  Category[] @relation("CategoryToCategory")
}


Default type produced:
type Category = {
    id: string;
    name: string | null;
    parentId: string | null;
}


Modified with GetPayload
type CategoryWithRelations = Prisma.CategoryGetPayload<{
  include: {
    parent: true;
    children: true;
  };
}>;

which just means:
type CategoryWithRelations = Category & {
    parent: Category | null;
    children: Category[]    
}

But children isn't recursive in this type ^^^ because it doesn't contain relations right?


Correct way?

Default type produced:
type Category = {
    id: string;
    name: string | null;
    parentId: string | null;
}


Modified with GetPayload
type CategoryWithRelations = Prisma.CategoryGetPayload<{
  include: {
    parent: true;
  };
}>;


Recursive - Is this the right way?
type CategoryWithRelationsRecursive = CategoryWithRelations & {
    children: CategoryWithRelations[]
}
Was this page helpful?