【问题标题】:How can i use SUBSTR mysql function in Typeorm with select (SOLVED)如何在 Typeorm 中通过 select 使用 SUBSTR mysql 函数(已解决)
【发布时间】:2022-10-14 15:02:29
【问题描述】:

我正在创建可以带来 3 个表关系结果的查询

this.invoicesRepo
      .createQueryBuilder('invoices')
      .innerJoinAndSelect('invoices.client', 'client')
      .innerJoinAndSelect('invoices.items', 'items')
      .select(['invoices.id', 'client.name'])
      .groupBy('invoices.id')
      .getMany();

返回这些结果

[
  {
    "id": 1,
    "client": {
      "name": "Goku"
    }
  }
]

但我想要这样的结果

 // I WANT RESULTS
[
      {
        "id": 1,
        "client": {
          "name": "Gok"  // just 3 start letters 
        }
      }
   ]

我为此目的编写了此查询,但它只是返回 id

this.invoicesRepo
      .createQueryBuilder('invoices')
      .innerJoinAndSelect('invoices.client', 'client')
      .innerJoinAndSelect('invoices.items', 'items')
      .select(['invoices.id', 'SUBSTR(client.name,1,3)']) // not working
      .groupBy('invoices.id')
      .getMany();

如何在 typeorm 和 mysql 中达到较高的结果

所以我可以把它总结成一个简单的问题,我如何在 typeorm 中编写这个查询

select SUBSTR(name,1,3),items.invoiceId from client
inner join invoices on invoices.clientId = client.id
inner join items on items.invoiceId = invoices.id
group by items.invoiceId;

【问题讨论】:

    标签: mysql nestjs typeorm


    【解决方案1】:

    我有一个解决方案

    对于使用 substr 函数,我们应该使用 typeorm 提供的 getRaw 函数 getRawOne() 和 getRawMany()

    所以查询将是这样的

    this.invoicesRepo
          .createQueryBuilder('invoices')
          .innerJoinAndSelect('invoices.client', 'client')
          .innerJoin('invoices.items', 'items')
          .select('invoices.id')
          .addSelect('SUBSTR(client.name,1,3)', 'client_name') //here
          .groupBy('items.invoiceId')
          .orderBy('invoices.created_at', 'ASC')
          .getRawMany();  //these is necessary if u using function like substr,concat etc
    

    输出

    [
      {
        "invoices_id": 1,
        "client_name": "Gok"
      },
      {
        "invoices_id": 2,
        "client_name": "Kha"
      },
      {
        "invoices_id": 3,
        "client_name": "Gok"
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 2022-06-18
      • 2011-11-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      相关资源
      最近更新 更多