首页 > 解决方案 > Inner Join 的部分选择

问题描述

我需要在现场选择一个服务,看:

  async find(): Promise<AccountEntity[]> {
    const result = await this.repository
      .createQueryBuilder("account")
      .select(['account', 'accountServices', 'service.description'])
      .leftJoinAndSelect("account.accountAndServices", "accountServices")
      .leftJoinAndSelect("accountServices.service", "service")
      .getMany();
    return result === undefined ? null : result;
  }

如何 ?请。我不希望出现空属性,并且我还想选择显示我需要的属性:

{
  "message": "",
  "success": true,
  "data": [
    {
      "id": 1,
      "name": "STONES TECNOLOGIA LTDA",
      "accountAndServices": [
        {
          "service": {
            "name": "Construção de uma casa",
          },
          "date_initial": "2021-08-01T07:39:18.000Z",
          "date_final": "2021-08-01T07:39:20.000Z",
          "value": "10.00",
          "created_by": 1,
          "is_active": true,
          "id": 1,
          "pay_day": 10,
          "nfse": 0,
          "created_at": "2021-08-01T07:39:27.000Z",
        },
        {
          "service": {
            "name": "Desenvolvimento de sistemas",
          },
          "date_initial": "2021-08-01T07:40:01.000Z",
          "date_final": "2021-08-01T07:40:02.000Z",
          "value": "20.00",
          "created_by": 1,
          "is_active": true,
          "id": 2,
          "pay_day": 20,
          "nfse": 0,
          "created_at": "2021-08-01T07:40:11.000Z",
        }
      ]
    }
  ],
  "errors": null
}

我只需要实体连接上的选择字段。

标签: javascriptnode.jsnestjstypeorm

解决方案


使用必须使用的 innerJoin 进行选择addSelect(...)

find函数不能操作任何数据,并且应该返回一个数组(AccountEntity如果没有找到则为空):

function find(): Promise<AccountEntity[]> {
    return this.repository
      .createQueryBuilder("a")
      .innerJoin("account.accountAndServices", "as")
      .innerJoin("accountServices.service", "s")
      .select(['a.id', 'a.name', 'a.status'])
      .addSelect(['as.date_initial', 'as.date_final', 'as.service_id', 'as.value', 'as.nfse', 'as.value', 'as.created_by', 'is_active', 'pay_day', 'created_at'])
      .addSelect(['s.name'])
      .getMany();
}

请注意,要从函数中获取结果,您必须使用await. try此外,用和包围它,catch以便更好地处理错误。例子:

try {
    const accounts: AccountEntity[] = await find();
} catch(error) {
    console.error(`Error: ${error}`);
}

要将数组转换AccountEntity为另一个对象

function transform(accounts?: AccountEntity[]) {
    return {
        message: "",
        success: accounts !== undefined,
        data: accounts,
        errors: null
    };
}

推荐阅读