As you note in your question you are using Parse.com. I haven't used Parse.com before, so what I'm suggesting may not work right out of the box, but a quick search in the documentation directed me to this link: https://parse.com/docs/relations_guide#manytomany-jointables
Join-tables allow you have many-to-many relations with information attached to the relation (e.g. vote (-1/+1), date, etc.)
What you need here are 2 entities (Post
and User
) which should be connected using a join-table Vote
that keeps track of the votes of each user towards that post. I would try something like this:
ParseUser currentUser = getCurrentUser();
ParseObject post = ... //This is the post where the user is going to vote on.
ParseObject currentVote = new ParseObject("Vote");
currentVote.put("voter", currentUser);
currentVote.put("post", post);
currentVote.put("date", new Date());
currentVote.put("vote", -1); //down-vote
currentVote.saveInBackground();
You can see where this is going.
I'm not sure how Parse.com handles constraints, but based on the query interface you may want to ensure that a user is only voting once on each post by running a query before adding the vote:
// set up the query on the Vote table
ParseQuery<ParseObject> query = ParseQuery.getQuery("Vote");
query.whereEqualTo("voter", ParseUser.getCurrentUser());
query.whereEqualTo("post", post);
// execute the query
query.findInBackground(newFindCallback<ParseObject>() {
public void done(List<ParseObject> votes, ParseException e) {
if(votes.length <= 0) {
//apply the vote as above
} else {
//user already voted
}
}
});
Hope this helps.