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']
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With