[英]How can I get a list of posts with the user who created them?
Post entity class contains a many to one relationship with my Users entity:发布实体 class 包含与我的用户实体的多对一关系:
@ManyToOne(() => Users, user => user.posts)
user: Users;
Users entity class contains a one to many relationship with my Post entity:用户实体 class 包含与我的 Post 实体的一对多关系:
@OneToMany(() => Post, post => post.user)
posts: Post[];
I have a query which returns the list of posts with the user:我有一个查询,它返回用户的帖子列表:
@Query(() => [Post])
async getAllUserPosts(@Ctx() context: MyContext) {
try {
const qb = getConnection()
.getRepository(Post)
.createQueryBuilder("p")
.innerJoinAndSelect("p.user", "u", "u.id = p.userID")
.where("p.userID = :id", { id: 7 })
.orderBy("p.datePublished", "DESC")
const posts = await qb.getMany();
console.log(posts)
return posts
} catch (e) {
console.log(e);
return null;
}
}
When I run the query it returns the following:当我运行查询时,它返回以下内容:
How can I return this data in GraphQL?如何在 GraphQL 中返回此数据? I have attempted the following:
我尝试了以下方法:
Well aren't I silly...好吧,我是不是很傻...
I forgot to add the type of field for each relationship:我忘了为每个关系添加字段类型:
@ManyToOne(() => Users, user => user.posts)
@Field(() => Users)
user: Users;
@OneToMany(() => Post, post => post.user)
@Field(() => [Post])
posts: Post[];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.