Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
stewart715 Avatar asked Dec 08 '22 12:12

stewart715


2 Answers

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

like image 183
Jan Aagaard Meier Avatar answered Dec 11 '22 07:12

Jan Aagaard Meier


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

or

order: [
   [sequelize.literal('created_at, id'), 'desc']
]
like image 31
Faris Rayhan Avatar answered Dec 11 '22 07:12

Faris Rayhan