Bagusflyer
Bagusflyer

Reputation: 12925

Handle one to many relation in Parse in iOS

I have this scenario:

One post could have many comments. So I create a Post class and a Comment class in Parse.com. Here are the definitions or the class and their data:

One post:

enter image description here

The post have two comments:

enter image description here

I want to retrieve the post with the first comment from a specific author. Here is my code:

PFQuery *query = [PFQuery queryWithClassName:@"Post"];
[query orderByAscending:@"createdAt"];

[query findObjectsInBackgroundWithBlock:^(NSArray *posts, NSError *error) {

    for (PFObject* obj in posts) {

        PFRelation* comments = [obj objectForKey:@"comment"];
        PFQuery* theQuery = [comments query];
        [theQuery whereKey:@"author" equalTo:@"John"];
        [theQuery getFirstObjectInBackgroundWithBlock:^(PFObject *comment, NSError *error) {

            NSLog(@"Post title=%@,body=%@", [obj objectForKey:@"title" ],[obj objectForKey:@"body"]);
            NSLog(@"Comment content=%@",[comment objectForKey:@"content"]);
        }];
    }
}];

I don't think it's efficient although it works. And it's hard to tell when the queries are finished because there are two nested asynchronized calls.

Does anybody have better solution? Thanks.

EDIT:

The reason I think it's not efficient is because there are nested queries. But I don't know how to get what I want by using Relation. Maybe I should not use Relation? Instead, I should assign ObjectId of Post to Comment class? (But this method is not as easy as Relation in inputing data)

Upvotes: 1

Views: 1207

Answers (1)

Bishoy Hanna
Bishoy Hanna

Reputation: 4589

Relation type is recommended for many to many while for one to many "pointer" and "array" are recommended

Upvotes: 1

Related Questions