Related table is not included in the generated graphql types #114
Replies: 2 comments 3 replies
-
Hi @MichalLytek ! First, thank you for making this awesome tool! You save my life. As you say, yes, we can use related table if we use related resolver this tool generate, however, this will cause N+1 problem in some situation isn't it? Let's say, we have Prisma schema like bellow. model Company {
id Int @id @default(autoincrement())
name String
staffs Staff[]
}
model Staff {
id Int @id @default(autoincrement())
name String
retired Boolean
companyId Int
company Company @relation(fields: [companyId], references: [id])
} this tool generate @TypeGraphQL.ObjectType("Company", {
isAbstract: true
})
export class Company {
@TypeGraphQL.Field(_type => TypeGraphQL.Int, {
nullable: false
})
id!: number;
@TypeGraphQL.Field(_type => String, {
nullable: false
})
name!: string;
staffs?: Staff[];
@TypeGraphQL.Field(_type => CompanyCount, {
nullable: false
})
_count!: CompanyCount;
} @TypeGraphQL.Resolver(_of => Company)
export class CompanyRelationsResolver {
@TypeGraphQL.FieldResolver(_type => [Staff], {
nullable: false
})
async staffs(@TypeGraphQL.Root() company: Company, @TypeGraphQL.Ctx() ctx: any, @TypeGraphQL.Args() args: CompanyStaffsArgs): Promise<Staff[]> {
return getPrismaFromContext(ctx).company.findUnique({
where: {
id: company.id,
},
}).staffs(args);
}
} This means a query to get related Staff called for every Company model we got. await prisma.company.findMany({
include:{
staff: {
where: {
retired: false
}
}
}
}); I suppose this Prisma code make single query so no N+1 problem, but even we use code like above, CompanyRelationsResolver call another query to get Staff model. @TypeGraphQL.Field(_type => [Staff], {
nullable: true
})
staffs?: Staff[]; I know related resolver this tool generate is wonderful, we can call even "where" query by using GraphQL query. |
Beta Was this translation helpful? Give feedback.
-
When we have a related object, it is not included in the generated GraphQL types. Would you consider to add a feature to include the related object when we run the generator?
On the second thought, if it adds the related object as type, we have to include it in the resolver. Otherwise, it will error if the related object is not nullable.
The best way I can think of is to add models for GraphQL and not to use the generated type? In that way, we can include the type with @field(type => [WhateverObjectName]). We probably don't need to expose all the fields in the database tables.
Here is the example.
This only generates raw fields. Not the field from the relationship.
Beta Was this translation helpful? Give feedback.
All reactions