2013-12-16 25 views
2

是否存在等价于Rails中'默认范围'的bookshelf.js(http://bookshelfjs.org/)?bookshelf.js相当于Rails的默认范围(在node.js中)

例如,可以说我有典型的“用户”:

User = Knex.Model.extend({ 
    tableName: 'users' 
}); 

我们还假设用户的表有“验证”一个叫布尔字段。我想知道的是,如果有一种方法可以有一个默认的范围,这样当我查询用户表,

collection.fetch().then(function(collection) { 
    // the collection contains only users with the verified = true attribute 
}) 

集合返回只包含用户的验证= true属性

+0

您能否阐述您的意思? Bookshelf是一个ORM,还有一个Rails,你可以从ActiveRecords继承。 –

+0

我刚刚创建了一个npm包来做到这一点。只需搜索npm安装书架范围并将其添加为插件即可。 – JTWebMan

回答

2

书架model(或任何主干模型)允许扩展实例属性和classProperties

classProperties直接附加到与ActiveRecord的作用域方法类似的构造函数。

您可以将verified方法添加到User模型的类属性中,如下所示。

User = Bookshelf.Model.extend({ 
    tableName: 'users' 
}, { 

    verified: function (options) { 
     options = options || {}; 
     return Db.Collection.forge([], {model: this}).query(function (qb) { 
      qb.where('verified', true); 
     }).fetch(options); 
    } 

}); 

并且像这样使用它。

User.verified().then(function(collection) { 
    // the collection contains only users with the verified = true attribute 
}); 
+0

这是一个很好的解决方案,因为它允许在运行时动态范围。我将使用这种方法。 –

0

这是在路线图上的东西,现在你可以这样做:

collection.query('where', 'verified', '=', true).fetch().then(function(collection) { 
    // the collection contains only users with the verified = true attribute 
}); 
0

你也可以简单地像缓存

的部分查询

然后总是使用它,我猜?

2

我只是建立一个NPM包,它使用名为bookshelf-scopes的书架插件来完成此操作。

var knex = require('knex')({ 
    client: 'sqlite3', 
    connection: { filename: "./mytestdb" } 
}); 

var bookshelf = require('bookshelf')(knex); 
bookshelf.plugin(require('bookshelf-scopes')); 

现在在您的模型中,您可以添加范围。

var TestModel1 = bookshelf.Model.extend({ 
    tableName: 'testmodel', 
    scopes: { 
    active: function(qb) { 
     qb.where({status: 'Active'}); 
    } 
    } 
});