Reputation: 554
I'm having a problem with the syntax of a NSPredicate. I have 3 entities: A, B and C. A has a many-to-many relationship to B. B has a many-to-many relationship to C. I want to fetch all managed objects in A that have at least one relationship with an object in B which, in turn, has a relationship with at least one object in C.
I have tried a few variations of SUBQUERY and ANY but I'm obviously not using the right syntax.
I have tried:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *ent = [NSEntityDescription entityForName:@"A" inManagedObjectContext:self.managedObjectContext];
fetchRequest.entity = ent;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(B, $b, $b.c.@count > 0).@count > 0)"];
That resulted in:
2014-06-30 09:07:12.143 My App[86086:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Keypath containing KVC aggregate where there shouldn't be one; failed to handle $b.jobs.@count'
Then:
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"ANY b.c.@count > 0"];
resulted in:
2014-06-30 09:10:14.403 My App[86186:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported function expression count:(b.c)'
Also:
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(B, $b, $b.c.@count > 0))"];
resulted in:
2014-06-30 09:17:25.883 My App[86218:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(SUBQUERY(B, $b, $b.c.@count > 0))"'
Finally:
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(B, $b, $b.c).@count > 0)"];
ended with:
2014-06-30 09:18:30.202 My App[86272:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(SUBQUERY(B, $b, $b.c).@count > 0)"'
Anyone has any idea? There must be an easy way to do this fetch...
Upvotes: 4
Views: 730
Reputation: 539685
This should work:
[NSPredicate predicateWithFormat:@"SUBQUERY(bs, $b, ANY $b.cs != NULL).@count > 0"]
where "bs" is the to-many relationship from entity A to B, and "cs" is the to-many relationship from B to C.
Upvotes: 2