-1

I have two models Practice and PracticeRecord with a to-many relationship between them. Now I want to retrieve an array of Practice objects whose number of associated practiceRecord objects are minimum but greater than zero. I wrote below code but it didn't work and exception happened when fetching the request. Can anybody give an elegant solution please. Thanks in advance.

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Practice"];

request.predicate = [NSPredicate predicateWithFormat:@"practiceRecords.@count > 0"];    

[request setResultType:NSDictionaryResultType];

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"practiceRecords.@count"];
NSExpression *minExpression = [NSExpression expressionForFunction:@"min:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"minPracticeRecordTimes"];
[expressionDescription setExpression:minExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
    // Handle the error.
}
else {
    if ([objects count] > 0) {
        NSLog(@"Minimum practice record times: %@", [[objects objectAtIndex:0]
                                    valueForKey:@"minPracticeRecordTimes"]);
    }
}

1 Answers1

0

I'd guess the issue is using an aggregate function (practiceRecords.@count) in the key path

If you consider the SQL this will generate, it'll be something like this:

SELECT min(count(practiceRecords)) AS minPracticeRecordTimes
FROM Practice
WHERE count(practiceRecords) > 0

which is of course invalid.

If you need to do this, maybe de-normalize your entities a bit, and add a count field to Practice, which is updated each time a PracticeRecord is added or removed, then you can use a straight fetch request.

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160