Backbone collection where clause with OR condition

余生长醉 提交于 2019-12-03 09:41:10

问题


I have searched for this for quite some time but could not get a way to have a where clause with or condition. For example if I have a collection Cars and I try to do the following:

Cars.where({
            model: 1998,
            color: 'Black',
            make: 'Honda' 
          })

So what the above will do is search for a car whose model is 1998 AND color is Black AND make is Honda.

But I require a way to get cars which have either of the three conditions true.


回答1:


Cars.filter(function(car) {
    return car.get("model") === 1998 ||
        car.get("color") === "Black" ||
        car.get("make") === "Honda";
});



回答2:


I know that this an old post, but maybe this could be useful to somebody.

I had a similar problem, but a little simplier, this how I solved it

var ids=[1,2,3,4];
var plans=this.collection.filter(function(plan){
            var rt=false;
            for(var i=0;i<this.whereOR.length;i++){
                rt=rt||plan.get('id')==this.whereOR[i];
            }
            return rt;
        },{whereOR:ids});

I think this could be adapted to solve the problem proposed like this:

var search={model: 1998,color: 'Black',make: 'Honda'};
Cars.filter(function(car){
                var rt=false;

                for(key in this.whereOR) {
                    rt=rt||car.get(key)==this.whereOR[key];
                }
                return rt;
            },{whereOR:search});)

Hope this help someone!



来源:https://stackoverflow.com/questions/14208044/backbone-collection-where-clause-with-or-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!