Darren
Darren

Reputation: 10398

How to write an iOS Parse query that compares two fields in the same table?

I have a parse table with 2 number fields and I need to create a query that pulls down only records where field2 is smaller than field1.

I tried this but it gives an exception that the predicate must have a key path and a constant:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"field2 < field1"];
PFQuery *query = [PFQuery queryWithClassName:parseRequestObject predicate:predicate];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    for (PFObject *object in objects) {
        NSLog(@"%@", object.objectId);
    }

}];

Upvotes: 1

Views: 516

Answers (1)

Darren
Darren

Reputation: 10398

It appears that the only way to query this is to fetch all the data and compare on the device. However I managed to get around it using cloud code that sets a bool when field2 becomes larger than field1. Now I can just query the BOOL field to get the records I need.

Parse.Cloud.beforeSave("MyObject", function(request, response) {
    var field1 = request.object.get("field1");
    var field2 = request.object.get("field2");

    if (field2 >= field1) {
        request.object.set("completed", true);
    }

    response.success();
});

Upvotes: 1

Related Questions