如何限制孩子留在Typeorm中?

问题描述 投票:0回答:1

我在 Nest.js 应用程序中将 TypeORM 与 PostgreSQL 结合使用。我有两个实体,用户和照片,具有一对多关系(一个用户可以拥有多张照片)。我正在尝试使用 TypeORM 的查询生成器检索用户以及每个用户最多 5 张照片。

postgresql nestjs typeorm
1个回答
0
投票

上次我有这个用例时,我用这种方式解决它(需要两个查询):

    // 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
© www.soinside.com 2019 - 2024. All rights reserved.