2013-12-16 24 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'}); 
    } 
    } 
});