我想知道使用 TypeORM 选择固定数量关系的最佳方法,例如,如果我有 UsersEntity 和 PublicationsEntity,用户有 100 多个出版物,而我只想选择其中的 10 个,那是什么?实现这一目标的最佳方法是什么?
几年前有人要求过类似的东西,但我无法做任何功能性的事情:https://github.com/typeorm/typeorm/issues/89
没有任何限制,我的代码如下所示:
return await getRepository(UsersEntity)
.createQueryBuilder('user')
.where('user.userName = :userName', { userName })
.leftJoinAndSelect('user.publications', 'publications')
.leftJoinAndSelect('publications.category', 'category')
.leftJoinAndSelect('publications.comments', 'comments')
.leftJoinAndSelect('comments.children', 'children')
.leftJoinAndSelect('publications.likes', 'likes')
.getOne();
答案 0 :(得分:0)
您可以按照他们在此主题中提到的两个查询来完成,方法如下:
const user = await getRepository(UsersEntity).createQueryBuilder('articles')
.where("user.userName = :userName", { userName })
.getOne()
user.publications = await getRepository(PublicationsEntity)
.createQueryBuilder("publication")
.where("publication.colmunuserid=:userId", { userId: user.id }) // replace colmunuserid with the correct name of the column
.leftJoinAndSelect('publication.category', 'category')
.leftJoinAndSelect('publication.comments', 'comments')
.leftJoinAndSelect('comments.children', 'children')
.leftJoinAndSelect('publication.likes', 'likes')
.limit(10)
.getMany()
return user;