'how to sort associated tables in sequelze?

I want to return an associated table, but sort those items. Nothing complicated like sorting by an associated table. Just sort the associated elements.

    public static async findWith(finder: any): Promise<Race | null> {
        const race = await Race.findOne({
            where: finder,
            include: [
                {
                    model: Rocket,
                    order: ['id', 'desc']
                }
            ]
        })
        return race
    }

I tried a few options,

order: ['id', 'desc']
order: [['id', 'desc']]
order: [[Rocket, 'id', 'desc']]. // nested

which are all accepted without error, but the sorting isn't applied.

research:

I'm using sequelize-typescript with v6 and postgres.



Solution 1:[1]

It is mentioned in sequelize documentation that if you want to apply ORDER clauses to eager loaded models, you must use the top level order option. Therefore, you should write it outside the include option like this

const race = await Race.findOne({
            where: finder,
            include: [
                {
                    model: Rocket
                }
            ],
            order: [[Rocket, 'id', 'desc']]
        })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Uzair Saeed