【问题标题】:Problem with left join with contition typeorm带有条件 typeorm 的左连接问题
【发布时间】:2022-09-25 19:33:39
【问题描述】:

这是我的代码:

 const query = this.requestRepository
      .createQueryBuilder(\'request\')
      .leftJoinAndMapMany(
        \'request.approvers\',
        RequestApprover,
        \'approvers\',
        \'request.id = approvers.requestId\',
      );

这是我从查询中获得的数据:

\"requests\": 
[
    {
        \"id\": \"8ceee413-521c-4e21-a75b-27048d184804\",
        \"status\": \"waiting\",
        \"reason\": \"1\",
         \"approvers\": [
             {
                 \"id\": \"04946109-ba35-4c08-a469-761023f33b3c\",
                 \"employeeCode\": \"EMP001\",
                 \"status\": \"waiting\",
            },
            {
                \"id\": \"a9dec055-e237-434c-897e-d877f64df4af\",
                \"employeeCode\": \"EMP002\",
                \"status\": \"approved\",
            }
        ]
    }
]

问题是当我添加条件以获取已被员工 EMP 002 批准的所有请求时

query.andWhere(`approvers.employeeCode = \'EMP002\'`)

缺少批准人[0]。我知道这是正确的,但我想知道是否有办法获得完整的批准者,但仍然可以获得 EMP002 是批准者的请求。感谢您的关注。

    标签: database typeorm


    【解决方案1】:

    您可以使用两个查询来执行此操作。首先,获取approvers.employeeCode = 'EMP002'所在请求的所有ids。然后获取所有requests,其中idrequest 等于上面获取的requestIds。

    const results = await this.requestRepository
        .createQueryBuilder('request')
        .leftJoinAndMapMany(
            'request.approvers',
            RequestApprover,
            'approvers',
            'request.id = approvers.requestId',
        )
        .select('request.id', 'id')
        .where('approvers.employeeCode = :empCode', { empCode: 'EMP002' })
        .getRawMany();
    const requestIds = results.map(e => e.id);
    const requests = await this.requestRepository
        .createQueryBuilder('request')
        .leftJoinAndMapMany(
            'request.approvers',
            RequestApprover,
            'approvers',
            'request.id = approvers.requestId',
        )
        .where('request.id IN (:...requestIds)', { requestIds: requestIds });
    

    requests 现在将包含所需的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多