Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 784
Shofiqul Alam Avatar asked Jul 06 '20 16:07

Shofiqul Alam


Video Answer


1 Answers

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

like image 146
Art Olshansky Avatar answered Sep 17 '22 16:09

Art Olshansky