Search code examples
iosswiftparse-platformpfquery

Parse.com - Fetching relation using Swift


I have a user favorites class that's storing a user object and an event object, it get set when a user favorites an event.

I'd like to display the full list of a given user's favorites. So I query favorites class to get the event objects and then attempt to query the events table to match the event object from favorite with the actual event class to pull in the event name and ID. In ruby for example, assuming relations/associations are setup, I would just call:

favorite.event.name
favorite.event.id

What's the equivalent in Swift? Here's what I have so far, but something tells me I'm overcomplexifying it and I would hope there's simple methods available for retrieving data through relations.

let query = PFQuery(className: "Favorite")
    query.includeKey("eventId")
    query.whereKey("createdBy", equalTo:userId!)
    query.findObjectsInBackgroundWithBlock { (favorites:[PFObject]?, error:NSError?) -> Void in

        if (error == nil){
            print("Favorite Count: \(favorites!.count)")
            print("Favorite Event IDs: \(favorites!)")

            for favorite in favorites! {
                print("Favorite: \(favorite)")

                let eventNameQuery = PFQuery(className: "Event")
                eventNameQuery.whereKey("eventId", equalTo:favorite )
                eventNameQuery.findObjectsInBackgroundWithBlock { (events:[PFObject]?, error:NSError?) -> Void in

                    if (error == nil){
                        print(events!.count)
                        print(events!)

                        for event in events! {                            
                            self.favoriteListItems.append(event.objectId! as String)  
                            self.favoriteListIds.append(event.objectId! as String) 
                        }
                    }
                }
            }
            self.savedEventsListTableView.reloadData()
        } else {  
            print("error fetching objects") 
        } 
    }  
}

When I run this, I get zero results...when I know in parse core I have objects that match both as shown below:

Favorite Class: Favorite Class with event object and user object

Event Class: Event Class


Solution

  • First of all query for a pointer to a User object, not user's objectId.

    query.whereKey("createdBy", equalTo:PFUser.currentUser()!)
    

    Next in here you probably want to add name of event.

    for event in events! {
     self.favoriteListItems.append(event["eventName"] as! String)
     self.favoriteListIds.append(event.objectId! as String)
    }