jmcastel
jmcastel

Reputation: 1365

How to chain constraint with parse PFQuery

Have a problem chaining constraint with parse PFQuery.

What i want :

I want to get all the photos around 50 km ordered by publication date. Latest first. (orderByDescending("createdAt")

If i don't put the location constraint, everything works good, as i have all my photos oredered by date.

When i put the whereKey for location, results are still ordered but for some reason, i can't have all the photos, some are skipped, and when i refresh, i never get the same result...

This is my code :

    var findPosts:PFQuery = PFQuery(className: "UserPost")

        findPosts.whereKey("location", nearGeoPoint: location, withinKilometers: 50)

        findPosts.orderByDescending("createdAt")
        findPosts.limit = 10
        findPosts.skip = timeLineData.count

Upvotes: 0

Views: 301

Answers (1)

Fogmeister
Fogmeister

Reputation: 77661

OK, from your last comment I think you're going to have to create a cloud code function to do this.

You'll need to write it in Javascript. The website has a load of documentation of how to create it.

You can create a function called something like nearestPosts and then have a parameter like skip and limit and location.

Except now, instead of relying on the PFQuery to do everything for you you can build the logic yourself.

So you can do something like...

  1. Fetch all the posts within 50 km of the location.
  2. Sort the posts in order of createdAt.
  3. Take the first limit number of posts starting after skip.
  4. Return these posts in an array.

Essentially it is doing what you want to do but you have to do it manually.

Then in iOS you can do something like...

[PFCloud callFunctionInBackground:@"nearestPosts"
                   withParameters:@{@"limit" : @10, @"skip" : @20, @"location" : geoPoint}
                            block:^(NSArray *posts, NSError *error) {
   if (!error) {
     // posts array contains the posts you need
   }
}];

There's lots of documentation of how to do stuff with Javascript on the Parse website.

Your Javascript will be something like this...

Parse.Cloud.define("nearestPosts", function(request, response) {
    var location = request.params["location"];

    getNearestPosts(location).then(function(posts) {
        response.success(posts);
    }, function(error) {
        response.error(error);
    });
});

function getNearestPosts(location) {
    var promise = new Parse.Promise();

    var query = new Parse.Query("UserPost");

    query.withinMiles("location", location, 50);

    query.find().then( function(results) {
        promise.resolve(results);
    }, function(error) {
        promise.reject(error);
    });

    return promise;
}

This will get all of the posts within 50 miles. And is just a start in how to get this all working.

Hope this helps.

Upvotes: 2

Related Questions