使用.orderBy()对Bookshelf.js结果进行排序

时间:2014-02-27 12:10:42

标签: node.js bookshelf.js

我正在开发一个学习Node.js + express + Bookshelf.js的个人项目。我在哪里构建查询?特别是,我如何在以下代码中设置'ORDER BY'或'WHERE'?

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

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

我想学习Bookshelf.js,因为它似乎提供了我习惯使用Laravel的Elequent(PHP)的功能,例如多态关系和子表达式。但是,我发现文档不是很深入,试图找到示例几乎是不可能的。

提前感谢您的帮助。

罗宾

3 个答案:

答案 0 :(得分:14)

我刚刚找到了问题的答案。

正如bookshelf.js网站所说,它使用knex.js查询构建器。所以要对我的收藏进行排序,这就是我所做的:

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

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

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

......效果很好!

答案 1 :(得分:11)

我知道这是一个老帖子,但这是我的看法。 BookshelfJS很棒,但它缺少一些简单的功能。所以我创建了自己的基础模型,名为Closet

对于orderBy,这就是Closet的样子:

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

我的其他模型花费Closet代替Bookshelf.Model。然后,您可以直接使用orderBy

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

答案 2 :(得分:10)

你也可以简单地做

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

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

无需访问查询构建器。