views:

513

answers:

3

Hello,

I have three entities: EntityA, EntityB and EntityC connected with to-many relationships.

See schema for details:

alt text

For getting all instance of EntityA which depend from EntityB.name I use the predicate like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY EntityB.name like 'SomeName'"];

What should be predicate for getting all instance of EntityA which depend from EntityC.name? I tried query like @"ANY EntityB.entitiesC.name like 'SomeName'" but get exception "multiple to-many keys not allowed here".

Best regards,

Victor

+1  A: 

Hello,

While I was stopped at the following decision:

First, I get all the EntityC that satisfy the condition EntityC.name equal to 'SomeName'

NSPredicate *p = [NSPredicate predicateWithFormat:@"name like %@", @"SomeName];

...

NSArray *res = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

Then I get an array of EntityB from above query

NSArray *parentBs = [res valueForKeyPath:@"@distinctUnionOfObjects.parent"];

Than get array of EntityB that satisfy the condition EntityB.EntitiesC.name equal to 'SomeName':

NSExpression *leftExpression = [NSExpression expressionForEvaluatedObject];
NSExpression *rightExpression = [NSExpression expressionForConstantValue:parentBs];

NSPredicate *p = [NSComparisonPredicate predicateWithLeftExpression:leftExpression rightExpression: rightExpression modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:0];

I repeat the same for EntityA.

The effectiveness of this solution in doubt and I still expect a better solution for this problem.

Victor
A: 

Check out this answer to the question Using NSPredicate with Core Data for deep relationships.

gerry3
A: 

My final solution is to use SUBQUERY.

NSPredicate *p = [NSpredicate predicateWithFormat:@"(name like %@) AND (0 != SUBQUERY(entitiesB, $x, (0 != SUBQUERY($x.entitiesC, $y, $y.name like %@).@count)).@count)", nameA, nameC];

Unfortunately I was unable to expand this query on nsExpression objects.

Victor