How can I sort relations loaded with find's "relations" option?
Problem
Issue type: [X] question [ ] bug report [ ] feature request [ ] documentation issue Database system/driver: [ ] `cordova` [ ] `mongodb` [ ] `mssql` [ ] `mysql` / `mariadb` [ ] `oracle` [X] `postgres` [ ] `sqlite` [ ] `sqljs` [ ] `react-native` [ ] `expo` TypeORM version: [X] `latest` [ ] `@next` [ ] `0.x.x` (or put your version here) Steps to reproduce or a small repository showing the problem: I'm loading an entity with a one-to-many relationship. So, that relationship is an array of entities associated with the entity I'm querying. I'd like to specify an order for that array of entities. Example (Users and their Photos): I'd like to query a user, load their photos as a relation, and the photos should be loaded by their createdAt date: [code block] Is there a way to do this?
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Sort Relations Loaded with TypeORM's Find Option
TypeORM does not support sorting of related entities directly through the 'relations' option in the find method. This limitation arises because the sorting of related entities must be handled after the initial query is executed, as TypeORM loads relations in a separate query without built-in sorting capabilities.
Awaiting Verification
Be the first to verify this fix
- 1
Define the Entity Relationship
Ensure that your entities are properly defined with the necessary relationships. For example, a User entity should have a one-to-many relationship with a Photo entity.
typescriptimport { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm'; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @OneToMany(() => Photo, photo => photo.user) photos: Photo[]; } @Entity() export class Photo { @PrimaryGeneratedColumn() id: number; @Column() createdAt: Date; @ManyToOne(() => User, user => user.photos) user: User; } - 2
Load User with Photos
Use the find method to load the user along with their photos. This will load the photos without any specific order initially.
typescriptconst user = await userRepository.findOne({ where: { id: userId }, relations: ['photos'] }); - 3
Sort Photos After Loading
Once the user and their photos are loaded, sort the photos array by the createdAt date. This can be done using JavaScript's array sort method.
typescriptif (user && user.photos) { user.photos.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()); } - 4
Return the Sorted User Object
Return the user object with the sorted photos array to the calling function or endpoint.
typescriptreturn user;
Validation
To confirm the fix worked, execute the code and check the returned user object. Ensure that the photos array is sorted by the createdAt date in ascending order. You can log the photos array to verify the order.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep