Skip to content

Commit

Permalink
feat(query-builder): allow ordering by custom expressions
Browse files Browse the repository at this point in the history
Closes #707
  • Loading branch information
B4nan committed Aug 10, 2020
1 parent 4585d86 commit e4674c7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/knex/src/query/QueryBuilderHelper.ts
Expand Up @@ -395,10 +395,10 @@ export class QueryBuilderHelper {
Utils.splitPrimaryKeys(field).forEach(f => {
const direction = orderBy[k];
const prop = this.getProperty(f, alias);
const noPrefix = prop && prop.persist === false;
const noPrefix = (prop && prop.persist === false) || QueryBuilderHelper.isCustomExpression(f);
const order = Utils.isNumber<QueryOrderNumeric>(direction) ? QueryOrderNumeric[direction] : direction;
const column = this.mapper(noPrefix ? f : `${alias}.${f}`, type);
const rawColumn = column.split('.').map(e => this.knex.ref(e)).join('.');
const rawColumn = Utils.isString(column) ? column.split('.').map(e => this.knex.ref(e)).join('.') : column;

ret.push(`${rawColumn} ${order.toLowerCase()}`);
});
Expand Down
6 changes: 6 additions & 0 deletions tests/QueryBuilder.test.ts
Expand Up @@ -1403,6 +1403,12 @@ describe('QueryBuilder', () => {
expect(qb.getQuery()).toEqual('select `e0`.* from `publisher2` as `e0` order by `e0`.`name` desc nulls last, `e0`.`type` asc nulls last');
});

test('order by custom expression', async () => {
const qb = orm.em.createQueryBuilder(Publisher2);
qb.select('*').orderBy({ 'length(name)': QueryOrder.DESC, 'type': QueryOrder.ASC });
expect(qb.getQuery()).toEqual('select `e0`.* from `publisher2` as `e0` order by length(name) desc, `e0`.`type` asc');
});

test('pg array operators', async () => {
const pg = await MikroORM.init<PostgreSqlDriver>({
entities: [Author2, Address2, Book2, BookTag2, Publisher2, Test2, BaseEntity2, Configuration2],
Expand Down

0 comments on commit e4674c7

Please sign in to comment.