diff --git a/packages/knex/src/query/QueryBuilderHelper.ts b/packages/knex/src/query/QueryBuilderHelper.ts index ca2ffec76551..ecbfd274a06f 100644 --- a/packages/knex/src/query/QueryBuilderHelper.ts +++ b/packages/knex/src/query/QueryBuilderHelper.ts @@ -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(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()}`); }); diff --git a/tests/QueryBuilder.test.ts b/tests/QueryBuilder.test.ts index 82b5864abdd9..10e50da5aba0 100644 --- a/tests/QueryBuilder.test.ts +++ b/tests/QueryBuilder.test.ts @@ -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({ entities: [Author2, Address2, Book2, BookTag2, Publisher2, Test2, BaseEntity2, Configuration2],