I'm trying to write a PFQuery
to get a user's friends as User objects. Shown below is my User table and Friend Lookup table. When a user creates a friendship, an entry is added into the Friend Lookup table.
My thinking is to build a query that queries the Lookup table for any row where the sendingUser
or receivingUser
is equal to the current user.
NSString * const kPULLookupSendingUserKey = @"sendingUser";
NSString * const kPULLookupReceivingUserKey = @"receivingUser";
....
PULUser *acct = [PULUser currentUser];
// query where sending user is current user
PFQuery *senderQuery = [PFQuery queryWithClassName:@"FriendLookup"];
[senderQuery whereKey:kPULLookupSendingUserKey equalTo:acct];
// query where receiving user is current user
PFQuery *recQuery = [PFQuery queryWithClassName:@"FriendLookup"];
[recQuery whereKey:kPULLookupReceivingUserKey equalTo:acct];
// query that ORs the previous two together and adds a couple more constraints
PFQuery *lookupQuery = [PFQuery orQueryWithSubqueries:@[senderQuery, recQuery]];
[lookupQuery whereKey:@"isBlocked" equalTo:@NO];
[lookupQuery whereKey:@"isAccepted" equalTo:@YES];
If I run just the lookupQuery
, it returns the correct rows where the current user is either the sender or receiver. I want to get that array of rows as User objects instead of FriendLookup objects.
Note PULUser
is a subclass of PFUser
// query for user where sending user key matches OID
PFQuery *userQuerySender = [PULUser query];
[userQuerySender whereKey:@"objectId" matchesKey:kPULLookupSendingUserKey inQuery:lookupQuery];
// query for user where receiving user key matches OID
PFQuery *userQueryRec = [PULUser query];
[userQueryRec whereKey:@"objectId" matchesKey:kPULLookupReceivingUserKey inQuery:lookupQuery];
// join queries together in an OR
PFQuery *query = [PFQuery orQueryWithSubqueries:@[userQuerySender, userQueryRec]];
// exclude self user from query
[query whereKey:@"objectId" notEqualTo:acct.objectId];
This returns an empty array. Any thoughts on how to properly form this query? Or is there a different approach to storing friendships that would make this task easier.
Use include key so the query results include the pointers to the 2 users, then form a set with all of the users and remove the current user, then you'll have all of the users without needing to make a secondary query.