Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to set order on include aggregate function alias in sequelize?

Below is my code

export async function getMany(page: number, recordsPerPage: number, condition: any = {}, order: any, attributes: string[] = [], other: object = {}) {
    try {
        let { count, rows }: any = await User.findAndCountAll({
            attributes: {
                include: [[sequelize.literal('(SELECT SUM(reputation) FROM scores where scores.user_id = User.id)'), 'reputation']],
                exclude: attributes,
            },
            where: condition,
            distinct: true,
            include: [
                {
                    model: Skill,
                    as: 'skills',
                    attributes: ['skill'],
                    through: { attributes: [] },
                },
            ],
            order: order,
            offset: page,
            limit: recordsPerPage,
            ...other,
            logging: console.log,
        });
        return { count, rows };
    } catch (e) {
        return false;
    }
}

I want to set order by reputation field which is alias of sum function column. i want my data in highest to lowest reputation.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply replace the order property with the given snippet. Worked for me.

order: [[sequelize.literal('table alias name goes here'), 'DESC']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading