Sort Bookshelf.js results with .orderBy()

2019-03-18 15:52发布

问题:

I am working on a personal project to learn Node.js + express + Bookshelf.js. Where do I build queries? In particular, how do I simply set an 'ORDER BY' or 'WHERE' in the following code?

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

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

I would like to learn Bookshelf.js because it seems to offer the features I am used to with Laravel's Elequent (PHP), such as polymorphic relationships and sub expressions. However, I'm finding that the documentation is not very in-depth and trying to find examples is near impossible.

Thanks in advance for any help.

Robin

回答1:

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!



回答2:

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
    });


回答3:

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.