Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: How to order by a relation field

Tags:

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

like image 841
Budget Avatar asked Sep 10 '19 13:09

Budget


People also ask

How do you use relations in TypeORM?

Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information.

What is getRepository TypeORM?

Repository is specific to an entity. In other words, each entity will have its own, build-in repository and it can be accessed using getRepository() method of connection object as specified below − const studRepository = manager.

What is join column in TypeORM?

Join columns are always a reference to some other columns (using a foreign key). By default your relation always refers to the primary column of the related entity. If you want to create relation with other columns of the related entity - you can specify them in @JoinColumn as well: @ManyToOne(type => Category)

Is TypeORM only for TypeScript?

TypeORM can be used not only with TypeScript, but also with JavaScript. Everything is the same, except you need to omit types and if your platform does not support ES6 classes then you need to define objects with all required metadata.


2 Answers

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(); 
like image 143
Software Person Avatar answered Nov 26 '22 05:11

Software Person


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 '%${seachValue}%' or action like '%${seachValue}%' or ip like '%${seachValue}%'`,       order: {         [sortField]: sortOrder === "descend" ? 'DESC' : 'ASC',       },       skip: (current - 1) * pageSize,       take: pageSize,     }); 
like image 40
Salah ED Avatar answered Nov 26 '22 05:11

Salah ED