问题
I'm using parse.com
, and I just want to know how to set and get relational data in a ParseObject
Subclass, for example like this.
Can you please give an example of field of type Relation
and show me how to set and get it in the subclass?
Thanks so much in advance !
回答1:
I'm not sure about what you are really asking. Relation
fields are sets of pointers to other ParseObject
. You don't have to add convenience methods in the subclass if you don't need to. The super class ParseObject
has all the methods necessary to interact with relation fields. The main entry point is getRelation("columnName")
, which you can use on any ParseObject
instance.
Let's say you have a AnywallPost
class and you have set a relation column, "likes"
, storing all ParseUser
s that like that post. Documentation is pretty clear in explaining how to get/set.
Set
You don't really set anything, you just add a new item in the relation field.
ParseRelation<ParseUser> relation = anywallPost.getRelation("likes");
relation.add(parseUser1);
relation.add(parseUser2);
anywallPost.saveInBackground();
A convenient method inside your subclass could be add(ParseUser user)
:
public void add(ParseUser user) {
ParseRelation<ParseUser> relation = this.getRelation("likes");
relation.add(user);
this.saveInBackground();
}
Then you can simply call anywallPost.add(parseUser)
.
Get
You don't really get anything, but rather you find items inside the relation. This is honestly well documented in the official docs. A useful method inside your subclass could give you the query:
public ParseQuery<ParseUser> getLikes() {
return this.getRelation("likes").getQuery();
}
Then you can use ParseQuery<ParseUser> q = anywallPost.getLikes()
and use the query as you wish.
来源:https://stackoverflow.com/questions/32056085/how-to-use-relation-fields-in-parse-com