저는 모델의 속성 중 하나를 사용하여 여러 컬렉션 중 하나에서 모델을 찾을 수있는 글로벌 검색을 만드는 아이디어를 가지고 놀고 있습니다.백본 멀티 콜렉션 글로벌 검색
나는이 다음 컬렉션 :
- 사용자
- 응용 프로그램
- 역할 내가 미리 각각의 사용자 속성을 모르는
, Applicaion 및 역할 예를 들어 설명 목적으로 가지고있을 것이다. 내가 가지고 있다고 말할 수있다 :
- User.name
- User.last_name
- User.email
- Application.Title이
- Application.description
- Role.name
- Role.description 이제
, 수 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;
}
이것은 예상 된 결과를 산출하고 나는 그것이 잘 작동 생각하지만, 그것은 나를 귀찮게 :
/// 몇 분 후 ... 여기
코드의 비트가 지금 막 시도이다 3 개 이상의 배열을 반복합니다. 다른 해결책이 없을 수도 있지만 거기에는 느낌이 있습니다. 누구든지 제안 할 수 있다면, 고마워요! 한편 나는 계속 연구 할 것이다.감사합니다.
우리는 [sphinx] (http://sphinxsearch.com/)에서도 성공을 거두었습니다. –