问题
I'm trying to figure out the best way to handle a one-to-many relationship using type-graphql and typeorm with a postgresql db (using apollo server with express). I have a user table which has a one-to-many relation with a courses table. The way I am currently handling this is to use the @RelationId field to create a column of userCourseIds and then using @FieldResolver with dataloader to batch fetch the courses that belong to that user(s). My issue is that with the @RelationId field, a separate query is made to get the relationids whether or not I actually query for userCourses. Is there a way to handle this where it won't make that extra query or is there a better way to go about handling one-to-many relationships?
User side of relation:
@OneToMany(() => Course, (course) => course.creator, { cascade: true })
userCourses: Course[];
@RelationId((user: User) => user.userCourses)
userCourseIds: string;
Course side of relation:
@Field()
@Column()
creatorId: string;
@ManyToOne(() => User, (user) => user.userCourses)
creator: User;
userCourses FieldResolver:
@FieldResolver(() => [Course], { nullable: true })
async userCourses(@Root() user: User, @Ctx() { courseLoader }: MyContext) {
const userCourses = await courseLoader.loadMany(user.userCourseIds);
return userCourses;
}
回答1:
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.
来源:https://stackoverflow.com/questions/63663128/best-way-to-handle-one-to-many-with-type-graphql-typeorm-and-dataloader