Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Orderby on multiple columns using typeorm

In my application, I am using MySQL and typeorm and want to do orderBy using multiple columns. I searched so many places for it but did not get any solution.

Example: I have two columns in a table user and respective User Entity

________________________________________
| id | name | createDate | createdTime |
----------------------------------------
| 1  | Sai  | 2020-12-12 | 12:20:30    |
........................................
| 2  | Ravi | 2020-12-13 | 13:20:30    |
........................................

Here, I want to orderBy createdDate and CreateTime both using typeorm something like below.

CM.getRepository(User)
      .createQueryBuilder('user')
      .select(["name", "id"])
      .orderBy('user.createdDate', 'ASC')
      .AndOrderBy('user.createdTime', 'ASC')

Please help me solve this.

Thank you...

like image 726
Sai Avatar asked Nov 04 '20 13:11

Sai


1 Answers

From TypeORM:

/**
 * Adds ORDER BY condition in the query builder.
 */
addOrderBy(sort: string, order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): this;

Just replace AndOrderBy to addOrderBy:

CM.getRepository(User)
      .createQueryBuilder('user')
      .select(["name", "id"])
      .orderBy('user.createdDate', 'ASC')
      .addOrderBy('user.createdTime', 'ASC') 
like image 123
Art Olshansky Avatar answered Nov 05 '22 21:11

Art Olshansky