Typeorm: How to order by a relation field

Budget picture Budget · Sep 10, 2019 · Viewed 17k times · Source

I have a Singer entity and a related Song entity

Singer entity

export class Singer {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany( type => Song, Song => Song.user )
    songs: Song[];

}

Song entity

export class Song {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToOne( type => Singer, Singer => Singer.songs )
    singer: Singer;

}

I want to get all Songs ordered by Singer name

I searched the docs and github issues but can't find an answer How can I solve this? better without QueryBuilder

Answer

Software Person picture Software Person · Sep 12, 2019

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();