Querying for 2 values in an array using Parse.com

I need to query parse.com to check if 2 specified values are present in an array.

The documentation states that: "You can give multiple constraints, and objects will only be in the results if they match all of the constraints. In other words, it's like an AND of constraints."

My experience says it is not.

I am querying like this:

NSString *user1 = [self.users objectAtIndex:0];
NSString *user2 = [self.users objectAtIndex:1];

NSLog(@"User 1: %@", user1);
NSLog(@"User 2: %@", user2);

PFQuery *gameQuery = [PFQuery queryWithClassName:@"GameObject"];
[gameQuery whereKey:@"users" equalTo:user1];
[gameQuery whereKey:@"users" equalTo:user2];

NSArray *gameObjects = [gameQuery findObjects];

NSLog(@"gameObjects: %@", gameObjects);

My log will say something like this:

2012-04-21 14:12:23.656 Cargo[5435:707] User 1: 689XXX62
2012-04-21 14:12:23.658 Cargo[5435:707] User 2: 51XXXX994

and

2012-04-21 14:12:24.614 Cargo[5435:707] GameObject: <GameObject:W7qXXXPLWp> {
  users =     (
     8XXX66,
     51XXXX994
  );
}

The query is clearly returning me an array of objects that match EITHER of the constraints. NOT both...

How can I solve this?

Upvotes: 4

Views: 2800

Answers (2)

Nur Iman Izam
Nur Iman Izam

Reputation: 1613

As detailed in PFQuery.h

Use this available method. This is ensure that EVERY object in specified array must be present.

- (void)whereKey:(NSString *)key containsAllObjectsInArray:(NSArray *)array;

Example

PFQuery *gameQuery = [PFQuery queryWithClassName:@"GameObject"];
[gameQuery whereKey:@"users" containsAllObjectsInArray:@[user1,user2]];

NSArray *gameObjects = [gameQuery findObjects];

Upvotes: 2

svintus
svintus

Reputation: 1672

From Parse header documentation:

/*!
  Add a constraint to the query that requires a particular key's object to be contained in the provided array.
 @param key The key to be constrained.
 @param array The possible values for the key's object.
 */
- (void)whereKey:(NSString *)key containedIn:(NSArray *)array;

You will call it like this:

[query whereKey: @"users" 
    containedIn: [NSArray arrayWithObjects: user1, user2, nil]];

Upvotes: 1

Related Questions