Nathan Day
Nathan Day

Reputation: 6037

any to-many to-many predicate

I can get a predicate like

ANY alpha.prop LIKE $SEARCH_TERM

to work where alpha is a to-many relationship, but how do I get

ANY alpha.beta.prop LIKE $SEARCH_TERM

to work where alpha is a to-many relationship and beta is a to-many relationship on alpha, this throws the exception 'multiple to-many keys not allowed here'.

Upvotes: 1

Views: 310

Answers (2)

Nathan Day
Nathan Day

Reputation: 6037

Ok the way to do this is to do the search on bottom child element instead so the query string becomes

prop LIKE $SEARCH_TERM

and then enumerate through the result and grab the parent of the parent and stick them in a set to remove duplicates, like

NSMutableSet  * mySet = [NSMutableSet set];
for( MyChild * c in [self.managedObjectContext executeFetchRequest:theFetchRequest error:&theError] )
{
    [mySet addObject:c.parent.parent];
}

Upvotes: 0

Martin R
Martin R

Reputation: 539685

You could do it in two steps. Let's assume that b is a one-to-many relationship from A to B and c is a one-to-many relationship from B to C, then you could first fetch all B objects that are related to any C object with the desired property:

NSFetchRequest *request1 = [NSFetchRequest fetchRequestWithEntityName:@"B"];
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"ANY(c.prop) LIKE %@", searchTerm];
request1.predicate = predicate1;
NSArray *bList = [context executeFetchRequest:request1 error:NULL];

Then fetch all A objects that are related to any B object from the intermediate result:

NSFetchRequest *request2 = [NSFetchRequest fetchRequestWithEntityName:@"A"];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"ANY(b) IN %@", bList];
request2.predicate = predicate2;

NSArray *aList = [context executeFetchRequest:request2 error:NULL];

Upvotes: 1

Related Questions