使用type-graphql typeorm和dataloader处理一对多的最佳方法 [英] Best way to handle one-to-many with type-graphql typeorm and dataloader
问题描述
我正在尝试找出使用type-graphql和typeorm与postgresql db(使用带有express的apollo服务器)处理一对多关系的最佳方法.我有一个用户表,它与课程表具有一对多关系.我当前处理此问题的方式是使用@RelationId字段创建一列userCourseIds,然后将@FieldResolver与dataloader配合使用以批量获取属于该用户的课程.我的问题是,无论我是否实际查询userCourses,都使用@RelationId字段进行单独的查询以获取相关ID.有没有一种方法可以解决不进行额外查询的情况,或者有更好的方法来处理一对多关系?
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?
关系的用户端:
@OneToMany(() => Course, (course) => course.creator, { cascade: true })
userCourses: Course[];
@RelationId((user: User) => user.userCourses)
userCourseIds: string;
关系的一面:
@Field()
@Column()
creatorId: string;
@ManyToOne(() => User, (user) => user.userCourses)
creator: User;
userCourses FieldResolver:
userCourses FieldResolver:
@FieldResolver(() => [Course], { nullable: true })
async userCourses(@Root() user: User, @Ctx() { courseLoader }: MyContext) {
const userCourses = await courseLoader.loadMany(user.userCourseIds);
return userCourses;
}
推荐答案
userCourses
字段可以使用
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;
}
将不再发出其他查询,因为省略了 userCourseIds
.尽管存在带有 @RelationId
的 creatorId
,但由于该实体具有自己的值,因此不会发出额外的查询.
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.
这篇关于使用type-graphql typeorm和dataloader处理一对多的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!