问题
I am writing an iOS app and I am using Parse to store data on the server side.
I have Users and each user can have a Car.
I am trying to figure out how to write a query that allows me to get all users that have a car with year less than 2000 and with a certain color (lets say red).
Each car has a relationship to the user and each user also has a relationship to their car.
User <-> Car (one to one)
I started using the PFQuery:
PFQuery * userQuery = [PFQuery queryWithClassName:@"User"];
I am not sure how to handle the relationship in the query. So, I'm pretty much not sure how to get this done.
Any suggestion?
回答1:
First off, the User
class is a special case, when using it in a query you need to do this:
PFQuery *query = [PFUser query];
Next, the way you construct the query you want depends where the pointer is. If the User has a car
property that is a pointer to the Car
then the query would be as follows:
PFQuery *userQuery = [PFUser query];
PFQuery *carQuery = [PFQuery queryWithClassName:@"Car"];
[carQuery whereKey:@"year" lessThan:@(2000)];
[carQuery whereKey:@"color" equalTo:@"red"];
[userQuery whereKey:@"car" matchesQuery:carQuery];
[userQuery includeKey:@"car"]
[userQuery findObjectsInBackgroundWithBlock:^(NSArray *users, NSError *error) {
for (PFObject *user in users) {
PFObject *car = user[@"car"];
// read user/car properties as needed
}
}];
If instead the Car
class has a user
property you just do a normal query and add the following line to let you access the full User
object:
[carQuery includeKey:@"user"];
回答2:
What does your table look like? If you have User as a column in your Car table, you can just query the car table for cars of year less than 2000 and then you would just access the User property of that query. It would look something like this:
PFQuery *carQuery = [PFQuery queryWithClassName:@"Car"];
[carQuery whereKey:@"year" lessThan:@(2000)];
[carQuery includeKey:@"user"];
[carQuery findObjectsInBackgroundWithBlock:^(NSArray *cars, NSError *error) {
if (!error) {
for (Car *car in cars) {
User *user = car@["user"];
}
}
}];
来源:https://stackoverflow.com/questions/24522089/parse-ios-how-query-object-by-properties-found-in-related-pfobject