Knex.js multiple orderBy() columns

谁都会走 提交于 2019-12-08 16:02:54

问题


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?


回答1:


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

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



回答2:


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.




回答3:


You can use the following solution to solve your problem:

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

sortArray.forEach(
  ({ field, direction }) => builder.orderBy(field, direction)
);


来源:https://stackoverflow.com/questions/36353837/knex-js-multiple-orderby-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!