Knex.js multiple columns orderBy ()

Is it possible to make multiple columns of orderBy ()?

knex .select() .table('products') .orderBy('id', 'asc') 

The orderBy () chain uses only one column key and sort value, but how can I sort by multiple columns?

+8
source share
2 answers

You can call .orderBy several times to order multiple columns:

 knex .select() .table('products') .orderBy('name', 'desc') .orderBy('id', 'asc') 
+18
source share

The original answer is technically correct and useful, but I wanted to find a way to programmatically apply the orderBy() function several times, here is the actual solution I went with for the link:

 var sortArray = [ {'field': 'title', 'direction': 'asc'}, {'field': 'id', 'direction': 'desc'} ]; knex .select() .table('products') .modify(function(queryBuilder) { _.each(sortArray, function(sort) { queryBuilder.orderBy(sort.field, sort.direction); }); }) 

Knex offers a change function that allows you to work directly with queryBuilder. The array iterator then calls orderBy() several times.

+7
source share

All Articles