views:

30

answers:

1

So I have typical 1:M relationship:

Car can have many Models

I want to get all Car objects and only Model names that begin with 'A'.

I tried a subquery:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(models, $model, $model.name BEGINSWITH 'A').@count > 0"];    
[fetchRequest setPredicate:predicate];

This would basically return a Car as long as it has a model that begins with 'A'. That's fine, but for all those Cars returned, it also returns all the Models, and I only want the ones that start with 'A'

But it seems as long as I operate on the higher level entity (Car), then that subquery only filters Cars and doesn't filter Models at all.

What I'm doing it now is filtering Models in an inner loop (using another NSPredicate), but I'd rather do this filtering on the SQL side.

Ideas?

A: 

Run your fetch against the Models entity with a predicate:

[NSPredicate predicateWithFormat:@"name BEGINSWITH 'A'"];

From the result array, NSArray *result, you can get all of the Cars with KVC:

[result valueForKey:@"car"];

assuming you have 1:1 inverse relationships for your 1:M Cars to Models relationship (you should, by the way; Core Data uses inverse relationships to maintain consistency of the object graph).

If you want just the set of unique Cars:

[result valueForKeyPath:@"@distinctUnionOfObjects.car"];

or

NSSet *cars = [NSSet setWithArray:[result valueForKey:@"car"]];
Barry Wark
Yeah, that's something I arrived at. Working via the Models entry first and then getting back the cars. I like your KVC method here.Thanks!
Maverick