Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 344
jakeatwork Avatar asked Jun 19 '26 23:06

jakeatwork


1 Answers

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)
}
like image 91
Juri Noga Avatar answered Jun 23 '26 00:06

Juri Noga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!