使用.orderBy()对Bookshelf.js结果进行sorting
我正在开发个人项目来学习Node.js + express + Bookshelf.js。 我在哪里构build查询? 特别是,如何在下面的代码中简单地设置“ORDER BY”或“WHERE”?
var Accounts = require('../collections/accounts').collection; new Accounts().fetch({ withRelated: ['folders'] }).then(function(collection) { // process results });
我想学习Bookshelf.js,因为它似乎提供了Laravel的Elequent(PHP)所使用的特性,例如多态关系和子expression式。 但是,我发现文档不是很深入,试图find例子几乎是不可能的。
在此先感谢您的帮助。
知更鸟
啊刚才find了我的问题的答案。
正如bookshelf.js网站所说,它使用knex.js查询生成器。 所以sorting我的collections这是我所做的:
var Accounts = require('../collections/accounts').collection new Accounts().query(function(qb){ qb.orderBy('name','DESC'); }).fetch({ }).then(function(collection){ // process results });
…这很好用!
我知道这是一个旧的post,但这是我的承担。 BookshelfJS是惊人的,但它缺乏一些简单的function。 所以我创build了我自己的基础模型,叫做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 });
你也可以简单的做
var Accounts = require('../collections/accounts').collection; new Accounts().query('orderBy', 'columnname', 'asc').fetch({ withRelated: ['folders'] }).then(function(collection) { // process results });
没有去查询生成器。