Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data Fetching Properties with Group By Count

This is the SQL version of the query I would like to write for Core Data:

SELECT Group.Name, COUNT(Item.Name)
FROM Item INNER JOIN Group ON Item.GroupID = Group.ID
GROUP BY Group.Name

So far what I have is:

NSFetchRequest* fetchGroupSummary = [NSFetchRequest fetchRequestWithEntityName:@"Item"];

NSEntityDescription* entity = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:[[CoreDataManager sharedInstance] managedObjectContext]];

NSAttributeDescription* groupName = [entity.relationshipsByName objectForKey:@"group"];
NSExpression *countExpression = [NSExpression expressionForFunction: @"count:" arguments: [NSArray arrayWithObject:[NSExpression expressionForKeyPath: @"name"]]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];

[expressionDescription setName: @"count"];
[expressionDescription setExpression: countExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"group.sort" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"group.stage == %@", stage];

[fetchGroupSummary setEntity:entity];
[fetchGroupSummary setSortDescriptors:@[sortDescriptor]];
[fetchGroupSummary setPropertiesToFetch:[NSArray arrayWithObjects:groupName, expressionDescription, nil]];
[fetchGroupSummary setPropertiesToGroupBy:[NSArray arrayWithObject:groupName]];
[fetchGroupSummary setResultType:NSDictionaryResultType];
[fetchGroupSummary setPredicate:predicate];

NSError* error = nil;
groups = [[[CoreDataManager sharedInstance] managedObjectContext] executeFetchRequest:fetchGroupSummary error:&error];

expressionDescription = nil;

This almost gives me everything, however instead of groupName being the group relationship I would like to specify group.name - is this possible?

Mark

like image 940
markpirvine Avatar asked Jan 03 '13 19:01

markpirvine


1 Answers

setPropertiesToGroupBy of NSFetchRequest accepts an array of NSPropertyDescription or NSExpressionDescription objects, or keypath strings. In your case, you can use a keypath string:

[fetchGroupSummary setPropertiesToGroupBy:[NSArray arrayWithObject:@"group.name"]];
like image 91
Martin R Avatar answered Dec 12 '22 03:12

Martin R