Knex.js multiple orderBy() columns

后端 未结 4 1162
天命终不由人
天命终不由人 2021-02-18 18:27

Is it possible to do multiple orderBy() columns?

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

The orderBy() chainable on

4条回答
  •  遇见更好的自我
    2021-02-18 19:20

    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.

提交回复
热议问题