Cameron Lowell Palmer
Cameron Lowell Palmer

Reputation: 22235

Writing an NSPredicate that filters results across several relationships

Below is a graph of relationships. I have a set of Recipes that I have retrieved and a set of BaseIngredients. I want to return a set of recipes that contain all of those ingredients. My current predicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@ AND ingredientSections.ingredients.baseIngredient IN %@", recipes, self.ingredientsFilter];

fails miserably. What is the correct way of doing this?

Object Graph

Upvotes: 0

Views: 74

Answers (1)

Martin R
Martin R

Reputation: 539685

With a nested to-many relationship, you probably need a SUBQUERY.

The following predicate returns all recipes where any base ingredient of any ingredient section is in the given set:

[NSPredicate predicateWithFormat:@"SELF IN %@ AND SUBQUERY(ingredientSections, $s, ANY $s.ingredients.baseIngredient IN %@).@count > 0",
     recipes, self.ingredientsFilter];

But unfortunately, that is not exactly what you need. To get all recipes that have a section containing all of the given ingredients, the following might work:

[NSPredicate predicateWithFormat:@"SELF IN %@ AND SUBQUERY(ingredientSections, $s, SUBQUERY($s.ingredients, $i, $i.baseIngredient IN %@).@count == %d).@count > 0",
     recipes, self.ingredientsFilter, [self.ingredientsFilter count]];

Upvotes: 1

Related Questions