Sort Bookshelf.js results with .orderBy()

依然范特西╮ 提交于 2019-12-03 06:04:33

Ah just found the answer to my question.

As the bookshelf.js website says, it uses knex.js query builder. So to sort my collection this is what I have done:

var Accounts = require('../collections/accounts').collection

new Accounts().query(function(qb){
    qb.orderBy('name','DESC'); 
}).fetch({

}).then(function(collection){
    // process results
});

... which works great!

I know this is an old post, but here is my take on it. BookshelfJS is amazing, but it lacks some simple features. So I have created my own base model, called Closet.

For orderBy, this is what Closet looks like:

var Closet = DB.Model.extend({

    /**
     * Orders the query by column in order
     * @param column
     * @param order
     */
    orderBy: function (column, order) {
        return this.query(function (qb) {
            qb.orderBy(column, order);
        });
    }
});

My other models expend Closet instead of Bookshelf.Model. Then you can directly use orderBy:

new Accounts()
    .orderBy('name', 'DESC')
    .fetch()
    .then(function(collection){
        // process results
    });

You can also simply do

var Accounts = require('../collections/accounts').collection;

new Accounts().query('orderBy', 'columnname', 'asc').fetch({
    withRelated: ['folders']
}).then(function(collection) {
    // process results
});

without getting to the query builder.

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