2

For simplicity sake, I have two classes Location and Program. Location has objectId and name, while Program has objectId, name and location (which is a pointer to Location ObjectId). When a user selects a location, how do I return the associated programs in a query? The following code doesn't work right now.

let pointer = PFObject(withoutDataWithClassName: "location", objectId: passedLocationID!) //passedLocationID is a string containing the ObjectId from the selected location    

let query = PFQuery(className:"Program")
query.whereKey("location", equalTo: pointer.objectId!)
query.findObjectsInBackgroundWithBlock {
    (objects: [PFObject]?, error: NSError?) -> Void in
    if error == nil {
        if let objects = objects {
            for object in objects {
                self.programName.append(object["name"] as! String)
                self.programID.append(object.objectId! as String)
            }
        }
    } else {
}

This query prints the following error to the console "pointer field location needs a pointer value"

What would the correct code be to return the associated programs?

EDIT

I have found a solution, but it seems like overkill. Two queries to Parse, I feel like this should be accomplished using only 1 query.

let firstQuery = PFQuery(className: "Location")
firstQuery.whereKey("objectId", equalTo: passedLocationID!)
    
let secondQuery = PFQuery(className: "Program")
secondQuery.includeKey("location")
secondQuery.whereKey("location", matchesQuery: firstQuery)
secondQuery.findObjects.......

2 Answers 2

2

So I found an answer.

When I pass the location to the program view controller, I need to pass it as a PFObject.

var passedLocationID: PFObject?

And then just a simple query works.

let newQuery = PFQuery(className: "Program")
newQuery.whereKey("location", equalTo: passedLocationID!)
Sign up to request clarification or add additional context in comments.

Comments

0

Adding the correct answer updated for Swift 3+ in case someone is searching:

guard let query = ProgramModel.query(), let pointerQuery = LocationModel.query() else {
   // Your parse class isn't set up correctly. Handle error.
   return
}

// You can also use other parameters like `notEqualTo` or `containedIn`.
pointerQuery.whereKey("objectId", equalTo: passedLocationId)

// The important line is the one below, which calls the pointer query:
query.whereKey("location", matchesQuery: pointerQuery)
query.includeKey("location")
query.findObjects... or query.countObjects...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.