Search code examples
iosswiftparse-platformpfrelation

Parse.com Get User Who Like an Object


So I've set up my relations correctly in Parse using the following code:

var user = PFUser.currentUser() var relation = user.relationForKey("likes") relation.addObject(self.post) user.saveInBackgroundWithBlock({ (Bool, error) -> Void in println("user likes this post") // Used for tracking in the PFTableCell for UI parts self.userLikes = true })

When the view loads, I need to change the buttons to Liked and the colour etc. I'd like to get all the users who liked this particular post but cannot figure out the query? It will give me some other useful info (e.g. I could display usernames of people who liked the post).

As a workaround I can get all the posts the user likes by doing:

var user = PFUser.currentUser()
var relation = user.relationForKey("likes")
relation.query().findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]!, error: NSError!) -> Void in
    if error != nil {
        // There was an error
        println(error)
    } else {
        // objects has all the Posts the current user liked and do something.
        println(objects)         
    }
}

But that's not what I'm after? I'm using Swift and the Parse SDK, but will happily have the answer in Obj C and I'll translate. The Parse docs suggestion is wrong: https://www.parse.com/docs/ios_guide#objects-pointers/iOS I could store the like against the post rather than the user, but that would mean I'd have to open up access rights to the post which is a no-no


Solution

  • There is an issue with your database structure. You should not just have User objects, but you should have Post objects as well. The Post can have a likes relation that points to all the Users who liked the post. When a User likes the Post, then the User is added to the Post's likes relation. Thus, to get the info you need, you just need to look at the Post's relation.

    What do you mean about open access rights to the Post? Do you want the post to be read only for all users except the User who posted it?

    Or is the issue with giving access to the User objects? I am not sure if it really an issue, since you could just be running a quick count on the User objects in the relation without actually looking at the data in the User objects. You could create Like objects, but I don't think it's necessary.