Search code examples
mysqlnode.jstypeorm

TypeORM select alias of column name


this.sampleRepo.find(
  {
    order: {
      id: "DESC"
    },
    select: ['id','group']
  }
);

this returns the id and group as expected, but how to return id as user_id ? and also how to select distinct values from group?


Solution

  • Just add an alias in you select string, e.g.:

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

    If the previous option didn't work, it should work in queryBuilder:

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

    I've made smth as you need with one of my examples (last one here) but wrote this (upd. fixed with getRawMany and distinct):

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

    and this works as you expect - results