How can I use NSPredicate to filter master data relationships?

Let's say I have basic data objects of type "obj" that have a property of "propertyA" and a one-to-many relationship with an object of type "sub" that has two properties: "propertyB" and "propertyC".

I want to get all objects that have property A equal to the value, and sub obj with property B and a set of properties.

If it were just property A and property B, I would do

[NSPredicate predicateWithFormat:@"ANY sub.propertyB = %@ AND propertyA == %@", ...];

The problem is that I cannot figure out how to add to the second property. I want only those objects that have at least one sub element that has two true properties. I tried the following, but it does not work:

[NSPredicate predicateWithFormat:@"ANY (sub.propertyB = %@ AND sub.propertyC) AND propertyA == %@", ...];

I tried this without ANYTHING, but this also doesn't work. How can i do this?

+5
source share
2 answers

Since you have a to-many relationship with a sub-object, the property subs objreturns a collection instead of a single object. To query a set, you need to use SUBQUERY.

Subqueries have the form:

SUBQUERY(collection, $individualCollectionItem, expression-with-collection-item)

in this case you need something like

SUBQUERY(subs,$s,$s.propertyB==%@) AND SUBQUERY(subs,$s,$s.propertyC!=NULL)
+7
source

The solution is similar:

[NSPredicate predicateWithFormat:@"propertyA == %@ AND (SUBQUERY(sub, $s, $s.propertyB == %@ AND $s.propertyC == %@).@count != 0)",  propertyAvalue, propertyBvalue, propertyCvalue];

where the values ​​at the end are the values ​​you want the different properties to be equal.

+4
source

All Articles