knshn's answer is not good because it's making the assumption that PFRelation
must be used anytime the "MANY" side has more than 100 relationships due to performance issues.
This is not true, because you can create a one-to-many relationship with "Pointer relations" and Parse can handle more than 100 relationships no problem. Or it can even effectively handle a many-to-many relationship with "Array relations" when one side has more than 100 relationships and the other one less than 100. So the correct answer should have mentioned that having more than 100 relationships becomes an issue ONLY when using "Array relations", ie. making an array with more than 100 items and setting it to an object.
So going back to the original question, I would suggest you to have an array of PFUser
players in the TennisGame
instance, because each game will have only 2 or 4 players at a time, or at least definitely less than 100.
Therefore, if you want to get the PFUser
players from a specific TennisGame
instance, you would have to perform a query like this:
PFQuery *query = [PFQuery queryWithClassName:@"TennisGame"];
[query includeKey:@"players"];
[query getObjectInBackgroundWithId:tennisGameId block:^(PFObject *tennisGame, NSError *error) {
if (tennisGame) {
tennisGame[@"players"];
}
}];
Next, if you want to get all the games played by your current user, sorted by date, you can perform the following query:
PFQuery *query = [PFQuery queryWithClassName:@"TennisGame"];
[query addDescendingOrder:@"createdAt"];
[query whereKey:@"players" equalTo:[PFUser currentUser]];
[query findObjectsInBackgroundWithBlock:^(NSArray *tennisGames, NSError *error) {
// do whatever you need with the results
}];
And finally, you may ask, "Wait! wouldn't be a performance issue if a player has played more than 100 games?" And the answer is no, because thats an issue for arrays only and not for queries. It would be an issue if the games were saved in the PFUser
instance as an array, instead of the players array being saved in the TennisGame
instance. Also, PFRelation
is some kind of query as well, so its the recommended way to retrieve large amounts of objects.
BONUS: When to use PFRelation
?
It's ideal when you need a A-LOT-to-A-LOT relationships, so using PFRelation
for something like "followers" on a social network app makes sense, because each account can have more than 100 "followers", and each account can be a "follower" to more than 100 other accounts.