Imagine the hypothetical case where I have a Car class that contains attributes like color, brand, etc. A car can have zero or more owners. The Owners class has first name, last name, etc attributes. When an owner is created, I set its "carID" attribute equal to a car's objectID. Therefore you can determine the number of owners a car has had by querying the Owners table where the carID equals a certain car ID.
Now I would like to perform a single fetch request that will return all attributes of a car, plus a new attribute that's not a column in the Car class. I want to get an array containing the owners objects associated with the car. The reason I want that info in a single request is because I am fetching multiple cars at once, so I don't want to have to make a request to get the owners for every single car that is returned from that fetch request.
This is my current query:
PFQuery *query = [PFQuery queryWithClassName:@"Car"];
[query whereKey:"color" equalTo:"red"];
[query findObjectsInBackgroundWithBlock:^(NSArray *cars, NSError *error) {
//need to know which owners each car has had so I can access attributes of each owner here
//without making a fetch request for every car in the "cars" array
}];
How would you modify the query in order to get the desired data in a single fetch?
Have your car representation include an attribute called owners which is an array of pointers to the owner class. With that, you can fetch owners eagerly as part of a car query using includeKey:
...
PFQuery *query = [PFQuery queryWithClassName:@"Car"];
[query includeKey:@"owners"];
[query findObjectsInBackgroundWithBlock:^(NSArray *cars, NSError *error) {
for (PFObject *car in cars) {
for (PFObject *owner in [cars objectForKey:@"owners"]) {
// here we'll enumerate all of the owners for all of the cars
}
}
}];
And you can get cars owned by a given owner with whereKey:equalTo:
, which works the same for singular and array columns...
PFObject *owner = // some owner
PFQuery *query = [PFQuery queryWithClassName:@"Car"];
[query whereKey:@"owners" equalTo:owner];
[query includeKey:@"owners"];
// etc.