Typeorm: How to order by a relation field Typeorm: How to order by a relation field typescript typescript

Typeorm: How to order by a relation field


I don't think it is currently supported by typeorm without the query builder, there is currently a feature request open

With the QueryBuilder it is quite simple though:

connection.createQueryBuilder(Song, 'songs')   .leftJoinAndSelect('songs.singer', 'singer')   .orderBy('singer.name', 'ASC')   .getMany();


You do not have to use the query builder if you are willing to do the ordering in-memory. (Careful: This implies fetching all data sets first and then conduct the filtering on your node server).

For this, you can delegate the task to a library like lodash. This way, you could still use the EntityManager or a Repository to query the data.

// first fetch the song and include (=join) the// singer by the foreign key "singer"var queryResult = await this.entityManager.find(Song, {  relations: ['singer'],});// then use a library like lodash to do the orderingconst songsSortedBySinger = _.orderBy(queryResult, song => song.singer.name);

For further reading:


You could do it with a workaround with entity hooks if the result is not too large:

  @AfterLoad()  sortItems() {    if (this?.sortableItems?.length) {      this.sortableItems.sort((a, b) => a.weight - b.weight);    }  }