Mikro-orm: [Docs] Query builder, repository and entity manager orderBy as string

Created on 1 Dec 2020  路  4Comments  路  Source: mikro-orm/mikro-orm

Is your feature request related to a problem? Please describe.
I cannot use complex "orderBy" expressions like ORDER BY FIELD(id, 3, 2, 4)

Describe the solution you'd like
orderBy() should accept string in addition to QueryOrderMap:

const results = await repo.find({ orderBy: 'FIELD(id, 3, 2, 4)'});

Describe alternatives you've considered
I've tried this workaround and found it very frustrating and eating my time:

    const chatsFromDbQb = await this.chatsRepo.createQueryBuilder('c').where({ id: { $in: chatIds } });
    const chatsFromDbKnex = chatsFromDbQb.getKnexQuery();
    chatsFromDbKnex.orderByRaw(`FIELD(c.id, ${chatIds.join(',')})`);

    const chatsFromDbKnexRes = await this.em.getConnection().execute(chatsFromDbKnex, [], 'all');
    const chatsFromDb = chatsFromDbKnexRes.map(a => this.em.map(ChatOrmEntity, a));
documentation

Most helpful comment

You can use custom statements in order by, here is one from the tests:

    const qb1 = orm.em.createQueryBuilder(Publisher2);
    qb1.select('*')
      .where({ name: 'test 123', type: PublisherType.GLOBAL })
      .orderBy({ [`(point(location_latitude, location_longitude) <@> point(${53}, ${9}))`]: 'ASC' });
    expect(qb1.getFormattedQuery()).toBe('select `e0`.* from `publisher2` as `e0` where `e0`.`name` = \'test 123\' and `e0`.`type` = \'global\' order by (point(location_latitude, location_longitude) <@> point(53, 9)) asc');

All 4 comments

You can use custom statements in order by, here is one from the tests:

    const qb1 = orm.em.createQueryBuilder(Publisher2);
    qb1.select('*')
      .where({ name: 'test 123', type: PublisherType.GLOBAL })
      .orderBy({ [`(point(location_latitude, location_longitude) <@> point(${53}, ${9}))`]: 'ASC' });
    expect(qb1.getFormattedQuery()).toBe('select `e0`.* from `publisher2` as `e0` where `e0`.`name` = \'test 123\' and `e0`.`type` = \'global\' order by (point(location_latitude, location_longitude) <@> point(53, 9)) asc');

@B4nan this should be reflected in the docs then, because it's not very intuitive :)

Yeah there are some hidden features for sure :] Where would you expect this information? I guess the QB and EM docs?

https://mikro-orm.io/docs/entity-manager/
https://mikro-orm.io/docs/query-builder/

I think those two pages can be a great place for this information 馃槍

Was this page helpful?
0 / 5 - 0 ratings