我正在玩弄创建一个全局搜索的想法,它允许我通过任何模型的属性在多个集合中的任何一个集合中找到任何模型。例如:
我有以下收藏:
- 用户
- 应用
- 角色
我不提前知道每个用户、应用程序和角色将具有哪些属性,但为了说明目的,可以说我有:
- 用户名
- User.last_name
- 用户邮箱
- 应用程序.title
- 应用程序描述
- 角色名称
- 角色描述
现在,假设我创建了Site
一个使用名为search
. 我想Site.search(term)
搜索每个集合中term
与任何属性匹配的所有项目。本质上是全局模型搜索。
你会建议我如何处理这个问题?我可以通过遍历所有集合的模型和每个模型的属性来暴力破解它,但这似乎臃肿且效率低下。
有什么建议么?
/// 几分钟后...
这是我刚才尝试的一些代码:
find: function(query) {
var results = {}; // variable to hold the results
// iterate over the collections
_.each(["users", "applications", "roles"], _.bind(function(collection){
// I want the result to be grouped by type of model so I add arrays to the results object
if ( !_.isUndefined(results[collection]) || !_.isArray(results[collection]) ) {
results[collection] = [];
}
// iterate over the collection's models
_.each(this.get(collection).models, function(model){
// iterate over each model's attributes
_.each(model.attributes, function(value){
// for now I'm only considering string searches
if (_.isString(value)) {
// see if `query` is in the attribute's string/value
if (value.indexOf(query) > -1) {
// if so, push it into the result's collection arrray
results[collection].push(model);
}
};
});
});
// a little cleanup
results[collection] = _.compact(results[collection]);
// remove empty arrays
if (results[collection].length < 1) {
delete results[collection];
}
},this));
// return the results
return results;
}
这产生了预期的结果,我想它工作正常,但我正在迭代三个数组,这让我很困扰。可能没有其他解决方案,但我有一种感觉。如果有人可以推荐一个,谢谢!同时我会继续研究。
谢谢!