Reputation: 537
Is anyone aware of how to combine OR statements with AND in Parse for iOS? So I essentially want to do something like this SQL statement:
select * from hotels where (city = 'New York' OR city = 'Chicago') AND (price < 1000 OR price > 2500)
There's a lot of documentation for combining a series of OR clauses in Parse using the orQueryWithSubqueries
method, but I've been unable to find anything solid for combining OR statements with the AND operator like this.
Upvotes: 0
Views: 471
Reputation: 2338
I believe you can make it easier using NSPredicate
:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city = 'New York' OR city = 'Chicago' AND price < @1000 OR price > @2500"];
PFQuery *query = [PFQuery queryWithClassName:@"Hotel" predicate:predicate];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
}];
Upvotes: 2
Reputation: 9911
I believe this sort of query is a bit of a pain with Parse, as you'll need to expand out the OR queries due to each of the OR queries needing to be complete. I think the below will probably do what you're after. (I'm guessing at your classname here too).
PFQuery *cheapNYQuery = [PFQuery queryWithClassName:@"Hotels"];
[cheapNYQuery whereKey:@"city" equalTo:"New York"];
[cheapNYQuery whereKey:@"price" lessThan:@1000];
PFQuery *expensiveNYQuery = [PFQuery queryWithClassName:@"Hotels"];
[expensiveNYQuery whereKey:@"city" equalTo:"New York"];
[expensiveNYQuery whereKey:@"price" greaterThan:@2500];
PFQuery *cheapCHQuery = [PFQuery queryWithClassName:@"Hotels"];
[cheapCHQuery whereKey:@"city" equalTo:"Chicago"];
[cheapCHQuery whereKey:@"price" lessThan:@1000];
PFQuery *expensiveCHQuery = [PFQuery queryWithClassName:@"Hotels"];
[expensiveCHQuery whereKey:@"city" equalTo:"Chicago"];
[expensiveCHQuery whereKey:@"price" greaterThan:@2500];
PFQuery *hotelQuery = [PFQuery orQueryWithSubqueries:@[cheapNYQuery, expensiveNYQuery, cheapCHQuery, expensiveCHQuery]];
// Run hotelQuery.
You could make the above more generic/reusable by using arrays of inputs for hotels and prices, and loop through them generating the queries for the OR, and adding them to a mutable array.
Upvotes: 2