9

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.

aditya_gaur
  • 3,209
  • 6
  • 32
  • 43

2 Answers2

11
Cars.filter(function(car) {
    return car.get("model") === 1998 ||
        car.get("color") === "Black" ||
        car.get("make") === "Honda";
});
Lukas
  • 9,765
  • 2
  • 37
  • 45
  • Hi @Lukas. Thanks for responding. But this is not what I was looking for. I had this solution in mind. The above example was just for illustration. The problem that I have is I am in a situation where I don't have the attributes of the model. I know I can get it by _.keys(model.attributes). But I was not willing to over complicate the filter function callback. It would have been great it there was a straight forward way. Appreciate all the help. Thanks – aditya_gaur Jan 08 '13 at 05:07
  • 1
    And I read your first implementation `Cars.where({model: 1998}).concat( Cars.where({color: "Black"}), Cars.where({make: "Honda"}) );`. This suited my situation better. But still looking for a clean solution. – aditya_gaur Jan 08 '13 at 05:09
  • Could you update the original post with more specifics on what you would like, then? Maybe we can still help you out here. – Lukas Jan 08 '13 at 05:49
0

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!

sebastian-greco
  • 118
  • 1
  • 5