我在 Nest.js 应用程序中将 TypeORM 与 PostgreSQL 结合使用。我有两个实体,用户和照片,具有一对多关系(一个用户可以拥有多张照片)。我正在尝试使用 TypeORM 的查询生成器检索用户以及每个用户最多 5 张照片。
上次我有这个用例时,我用这种方式解决它(需要两个查询):
// 1. Fetch all users
const users= await this.userRepo
.createQueryBuilder("user")
.getMany();
// 2. Loop through users and fetch photos with limit
for (let user of users ) {
user.photo = await this.photoRepo
.createQueryBuilder('photo')
.where('photo.user= :id' , {user.id});
.limit(5) // Set the desired limit here
.getMany()
}
//return users