简体   繁体   中英

Relation query in Parse.com

This is a basic question, but I can't understand how the relationship works in Parse.

I have this relationship: Image link

Briefly, it is a relationship 1 - N. One FeedPost have several comments.

I wish I can send the post ID in the Query and just get the araylist of comments on that post.

    ParseQuery<ParseObject> innerQuery = ParseQuery.getQuery("Comments");
    innerQuery.whereExists("UXKFwWyn3l"); //ID of the post
    ParseQuery<ParseObject> query = ParseQuery.getQuery("FeedPost");
    query.whereMatchesQuery("objectId", innerQuery);

Anyone can help me?

With this line

innerQuery.whereExists("UXKFwWyn3l"); 

you are saying "all records that have a value in the column 'UXKFwWyn3l'"

Also, you are using PFRelation when you should rather use pointers. In Comment, you should have a column with a pointer to the FeedPost. If you did, this query would get you the comments you want, providing you have the FeedPost object already:

ParseQuery<ParseObject> query = ParseQuery.getQuery("Comments");    
query.whereEqualTo("post", thePostObject );
query.findInBackground(new FindCallback<ParseObject>() {
    public void done(List<ParseObject> comments, ParseException e) {
        if (e == null) {
            // "comments" is now a list of the comments
        } else {
            // Something went wrong...
        }
    }
});

You can also have a reverse relationship in FeedPost, which should be an array of pointers to the comments (not a PFRelation). If you do, you can get both the FeedPost and the comments with one query:

ParseQuery<ParseObject> query = ParseQuery.getQuery("FeedPost");
query.include("comments"); // this is the column with an array of pointers to comments
query.getInBackground("UXKFwWyn3l", new GetCallback<ParseObject>() {
  public void done(ParseObject feedPost, ParseException e) {
    if (e == null) {
      // Your feedPost now has an array with all the comments
    } else {
      // something went wrong
    }
  }
});

You should only use PFRelation for advanced relations (like many-to-many).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM