Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

seepel

macrumors 6502
Original poster
Dec 22, 2009
471
1
I have an entity (parent) with a field (name) and a to-many relationship (child). What I would ultimately like to get is a fetch like


Code:
SELECT name, count(*) 
FROM parent 
JOIN child 
ON parent.pk = child.parent_fk 
GROUP by name 
ORDER by count(*) DESC;

So that it would output something like this

Code:
Parent_1|193
Parent_2|44
Parent_3|31
Parent_4|31
Parent_5|30
Parent_6|25

My first attempt was to do something along the lines of (assume I have a valid NSManagedObjectContext named context ... because I do)
Code:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:@"parent" inManagedObjectContext:context];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"child.@count" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];
NSArray *parents = [results valueForKey:@"name"];
NSArray *numberOfChildren = [results valueForKey:@"child.@count"];
[request release];
[sortDescriptor release];

I expected I would get an NSArray parents with the content from the first column of my SQL statement, and an NSArray numberOfChildren with the content from the second column of my SQL statement. Instead I got an exception

Code:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle child.@count'

I also tried the reverse
Code:
@count.child

and got the exception
Code:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath @count.child not found in entity <NSSQLEntity parent id=3>'

Does anyone have a suggestion as to how I could procede? I'd like to not fault in the child entities which I thought would be possible through this method.

Thanks
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.