FG
๐Ÿ—„๏ธ Databases

How can I sort relations loaded with find's "relations" option?

Freshabout 20 hours ago
Mar 14, 20260 views
Confidence Score95%
95%

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

Canonical Fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Sort Relations Loaded with TypeORM's Find Option

Low Risk

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. 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.

    typescript
    import { 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. 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.

    typescript
    const user = await userRepository.findOne({
      where: { id: userId },
      relations: ['photos']
    });
  3. 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.

    typescript
    if (user && user.photos) {
      user.photos.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
    }
  4. 4

    Return the Sorted User Object

    Return the user object with the sorted photos array to the calling function or endpoint.

    typescript
    return 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

AC

Alex Chen

2450 rep

Tags

typeormormtypescriptquestioncomp:-relationsdriver:-postgrescomp:-find-options