Knex.js multiple orderBy() columns

2020-07-01 16:30发布

Is it possible to do multiple orderBy() columns?

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

The orderBy() chainable only takes a single column key and a sort value, but how can I order by multiple columns?

4条回答
贪生不怕死
2楼-- · 2020-07-01 16:54

The Knex orderBy function also receives an array:

knex('users').orderBy(['email', 'age', 'name'])

or

knex('users').orderBy(['email', { column: 'age', order: 'desc' }])

or

knex('users').orderBy([{ column: 'email' }, { column: 'age', order: 'desc' }])
查看更多
走好不送
3楼-- · 2020-07-01 16:57

You can use the following solution to solve your problem:

const builder = knex.table('products');

sortArray.forEach(
  ({ field, direction }) => builder.orderBy(field, direction)
);
查看更多
Evening l夕情丶
4楼-- · 2020-07-01 17:02

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

knex
  .select()
  .table('products')
  .orderBy('name', 'desc')
  .orderBy('id', 'asc')
查看更多
叼着烟拽天下
5楼-- · 2020-07-01 17:05

The original answer is technically correct, and useful, but my intention was to find a way to programatically apply the orderBy() function multiple times, here is the actual solution I went with for reference:

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 modify function which allows the queryBuilder to be operated on directly. An array iterator then calls orderBy() multiple times.

查看更多
登录 后发表回答