Typeorm: How to order by a relation field
This is supported as of TypeORM 0.3.0:
songRepository.find({
order: {
singer: {
name: "ASC"
}
}
})
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();
Try the default order on the entity model
https://github.com/typeorm/typeorm/blob/master/sample/sample30-default-order-by/entity/Post.ts
@Entity("sample30_post", {
orderBy: {
title: "ASC",
id: "DESC"
}
})
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
}
I had the same issue i tried to order by custom column but without query builder because i was using Repository, this is my solution :
let res = await this.trackingRepository.findAndCount({
where: [{ username : Like(`%${searchValue}%`) },
{ action : Like(`%${searchValue}%`) },
{ ip : Like(`%${searchValue}%`) }],
order: {
[sortField]: sortOrder === "descend" ? 'DESC' : 'ASC',
},
skip: (current - 1) * pageSize,
take: pageSize,
});