【问题标题】:TypeORM select alias of column nameTypeORM 选择列名的别名
【发布时间】:2020-10-26 20:16:01
【问题描述】:
this.sampleRepo.find(
  {
    order: {
      id: "DESC"
    },
    select: ['id','group']
  }
);

这会按预期返回idgroup,但是如何将id 作为user_id 返回? 以及如何从组中选择不同的值?

【问题讨论】:

  • 1) id as user_id:目前您不能或至少不能将值映射为实体类的列名。见@Column装饰器name选项。
  • 我看到了列名选项,但正在考虑如果您需要在两个不同的 api 中发送两个不同的名称该怎么办,例如在 api A 中,我想在 api B 中将 id 作为用户 ID 发送,我想将 id 作为 id 发送。列名装饰器在这里无济于事。
  • 2) 您必须使用 QueryBuilder。有一个未解决的问题,请参阅 this,为实体管理器查找选项添加 distinct。
  • 您想要重新映射吗?为此: 1) 查找数组中的所有实体 2) Map 数组以重命名标识 -> 请注意,这是一个非常糟糕的过程,因为它具有 O(n) 复杂性并减少了 API 的正确语义。我强烈建议选择一种标识符以避免效率问题和更多未来问题。
  • 生产标识符将是一个,我只是要求学习如何在需要时做事。

标签: mysql node.js typeorm


【解决方案1】:

只需在您选择的字符串中添加一个别名,例如:

select: ['id AS user_id','group AS user_group']

如果上一个选项不起作用,它应该在 queryBuilder 中起作用:

this.sampleRepo
      .createQueryBuilder('user')
      .orderBy('user.id', 'DESC')
      .select(['id AS user_id','group AS user_group'])
      .getRawMany() // or .getMany()


我已经用我的一个例子 (last one here) 做了你需要的东西,但是写了这个(更新。用 getRawMany 和不同的方式修复)

getMany(): Promise<UserEntity[]> {
    return this.userRepo.createQueryBuilder('user')
      .where({ username: 'breckhouse0' })
      .select(['DISTINCT (user.username) AS user_name', 'user.id AS user_id'])
      .getRawMany();
  }

这正如你所料 - results

【讨论】:

  • 现在它适用于查询生成器,但对于实体管理器,它不起作用。请在带有用户名列的查询中添加 distinct 选项,不接受答案。
  • 我已经接受了答案,你能帮我提一点吗,如何在 find 方法中进行查询,比如我想查询用户 ID 为 1 或 2 的查询,为此我给出了return this.userRepository.find( { where : { id: In ["1","2"] } } );但它不起作用,我的目标是让所有 id 为 1 或 2 的用户。
  • 你错过了圆括号In() - return this.userRepository.find( { where : { id: In(["1","2"]) } } )
猜你喜欢
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多