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

use*_*128 11 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
});
Run Code Online (Sandbox Code Playgroud)

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

在此先感谢您的帮助.

知更鸟

use*_*128 15

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

正如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
});
Run Code Online (Sandbox Code Playgroud)

......效果很棒!


Kou*_*sha 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);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

我的其他模型Closet代替了Bookshelf.Model.然后你可以直接使用orderBy:

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


Vah*_*yan 10

你也可以干脆做

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

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

无需访问查询构建器.