Best way to handle one-to-many with type-graphql typeorm and dataloader
userCourses
field can be written like below using @TypeormLoader
decorator provided by type-graphql-datalaoader.
@ObjectType()@Entity()class User { ... @Field((type) => [Course]) @OneToMany(() => Course, (course) => course.creator, { cascade: true }) @TypeormLoader((course: Course) => course.creatorId, { selfKey: true }) userCourses: Course[];}@ObjectType()@Entity()class Course { ... @ManyToOne(() => User, (user) => user.userCourses) creator: User; @RelationId((course: Course) => course.creator) creatorId: string;}
Additional queries will not be issued anymore since userCourseIds
is omitted. Although creatorId
with @RelationId
exists, it will not issue extra queries since the entity has the value by its own.
Update: June 2021
@TypeormLoader
no longer needs arguments. Therefore @RelationId
can be completely omitted, if preferred.