How does Parse.com create a bidirectional relation

2019-06-14 11:43发布

I'm following this tutorial: https://parse.com/tutorials/one-to-many-relationships

I see a Post is created and the current user attached. But I don't see the opposite, I don't see how the Post is attached to the user. And at the end it says: "The application should now be able to create Post objects, set a one-to-many relationship between Posts and PFUsers, as well as use a query to obtain all Posts associated with a given user." How is that possible? If I use that code, how can I retrieve all Posts that belong to a User if I never attached the Post to its User? Thanks in advance!

2条回答
成全新的幸福
2楼-- · 2019-06-14 11:49

you can set the user as the post_owner of the post and query for posts that has the current user as their owner

查看更多
3楼-- · 2019-06-14 11:58

Parse is not a pure relational database, this is not the natural way to do it.

The usual is define a pointer type in your child table, pointing out to the father table.

    // Create a new Post object and create relationship with PFUser
PFObject *newPost = [PFObject objectWithClassName:@"Post"];
[newPost setObject:[textView text] forKey:@"textContent"];
[newPost setObject:[PFUser currentUser] forKey:@"author"]; // One-to-Many relationship created here!

// Set ACL permissions for added security
PFACL *postACL = [PFACL ACLWithUser:[PFUser currentUser]];
[postACL setPublicReadAccess:YES];
[newPost setACL:postACL];

// Save new Post object in Parse
[newPost saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (!error) {
        [self dismissViewControllerAnimated:YES completion:nil]; // Dismiss the viewController upon success
    }
}];

There is not this natural way of SQL access through subselects or Join.

But if you need to create a bidirectional relationship, you can do it by doing this.

https://parse.com/questions/bidirectional-relationship-one-to-many

查看更多
登录 后发表回答