简体   繁体   中英

node sequelize sort by multiple columns

Coming from a Ruby/Rails background, I'm used to this type of syntax:

Model.all.order('col1 + col2 + col3')

So, given that col1, col2 and col3 are integers, for example, it would sort the results by the sum of those 3 columns.

Is there a similar way to sort like this using sequelize?

With the latest master (not sure if the change has been pushed to npm yet), you can do the following:

Model.findAll({ order: [[{ raw: 'col1 + col2 + col3 DESC' }]]});

Resulting in

ORDER BY col1 + col2 + col3 DESC

Or you can do:

Model.findAll({ order: [[sequelize.fn('SUM', sequelize.col('col1'), sequelize.col('col2'), sequelize.col('col3')), 'DESC']]});

Resulting in

ORDER BY SUM(`col1`, `col2`, `col3`) DESC

I would recommend the second version, which will properly escape the column names. For more info see http://sequelizejs.com/documentation#models-finders-limit---offset---order---group

order: [
   ['created_at', 'desc'],
   ['id', 'desc']
]

or

order: [
   [sequelize.literal('created_at, id'), 'desc']
]

Had to sort by a col1+col2 in my model's defaultScope, the SUM solution provided as answer returned a sequelize error function sum(numeric, numeric) does not exists (or something similar).

My current workaround :

order: [[ 'col1', sequelize.literal('+'), 'col2', 'DESC']]

which will print out

ORDER BY "tableName"."col1"+"col2" DESC

just add more interspaced columns and sequelize.literal('+') for more columns.

If using includes/joins and you need all columns to be called with the table name... I tried sequelize.col('col2') but the table name wasn't added. I guess a combination like 'tableName', sequelize.literal('.'), 'columnName' should work, but you need to know your tableName/alias. And I couldn't access my model since it was being defined in my use case. The {model: 'model', as: 'alias'} from the documentation failed too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM