Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2Firebase query by multiple values whereIN

Tags:

So I'm looking for the equivalent of WHERE IN(val1,val2) I have tried like this but doesn't work.

Angular Firebase

this.firebase.database.list('/favorites', {
            query: {
                orderByChild: 'uID',
                equalTo: [1,2,3,'some value]
            }
});
like image 749
Uffo Avatar asked Feb 17 '18 20:02

Uffo


2 Answers

Firebase's queries don't have an OR or IN operator. So you cannot easily map the above query to Firebase.

One workaround would be to implement multiFilter over the elements:

public items: FirebaseListObservable<any[]> = null;


ngOnInit() {
    this.items = this.db.list('/favorites', {
        query: {
            orderByChild: 'uID'  
        }
    });

    this.items.subscribe(items => {
       console.info(this.multiFilter(items,{'uID': [1,2,3,'some value]}));
    });
}

public multiFilter(arr: Object[], filters: Object) {
  const filterKeys = Object.keys(filters);
  return arr.filter(eachObj => {
    return filterKeys.every(eachKey => {
      if (!filters[eachKey].length) {
        return true; // passing an empty filter means that filter is ignored.
      }
      return filters[eachKey].includes(eachObj[eachKey]);
    });
  });
};
like image 200
Rahul Tank Avatar answered Sep 22 '22 13:09

Rahul Tank


I would have the users under a users node.

Generally the IDs would be the firebase pushKeys.

so user > userId > { user information }.

Then have businesses

business > businessId > { business information }

then a business to user node.

businessForUser > userId > businessId = true

So you would then fetch the list of businessIDs for the user from the businessForUser node and then fetch the business information from the business node with those fetched IDs.

like image 41
Jesse Te Weehi Avatar answered Sep 20 '22 13:09

Jesse Te Weehi