I have following CoreData objects Model
Now I am having issue in making a predicate with following conditions.
Fetch all those DBOpportunity
WHERE
DBOpportunity.stateCode == 1
AND
DBOpportunity.invoiceDate >= GIVEN_DATE
AND
DBOpportunityLines.crmAccept == 1 OR DBOpportunityLines.crmAccept == 3
I have tried lots of examples and programming guide by the apple but can't able to achieve this.
opportunitylines
is a to-many relationship, so there are multiple DBOpportunityLines objects for one DBOpportunity object. Assuming that the last condition
DBOpportunityLines.crmAccept == 1 OR DBOpportunityLines.crmAccept == 3
should hold for any of the related objects, you need a SUBQUERY:
NSDate *givenDate = ...;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stateCode == 1 AND invoiceDate >= %@ "
"AND SUBQUERY(opportunitylines, $x, $x.crmAccept == 1 OR $x.crmAccept == 3).@count > 0",
givenDate];
Remark: Unfortunately, the usage of SUBQUERY in predicates is poorly documented. There is one example in the NSExpression class reference. See also Quick Explanation of SUBQUERY in NSPredicate Expression.