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"]);
}
}