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

Time:04-20

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.

CodePudding user response:

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

order: [[sequelize.literal('table alias name goes here'), 'DESC']]
  • Related