I have a Core Data entity, OrderItem that has a to-many relationship to another entity, OrderItemOption. I want to find a specific OrderItem that has a relationship to two specific OrderItemOptions. How do I do that in Core Data?
OrderItemOptions has a typecode and optioncode, essentially a key/value. I’m looking for an orderItem with an option (typecode=OptionSet1, optionCode=BT) and another option (typecode=OptionSet2, optionCode=CT).
The issue is how to distinguish the first OrderItemOption object and the second in the query.
I was able to come up with a SQL query to do exactly what I want. It uses aliases to perform a join the table with itself. How do I do the equivalent in Core Data?
The sql statement is:
select * from zorderItem, zorderItemOption one, zorderItemOption two where
one.zorderitem = zorderItem.z_pk and
one.zoptiontypecode='OptionSet1' and one.zoptioncode='BT' and
two.zorderitem =zorderitem.z_pk and
two.zoptiontypecode='OptionSet2' and two.zoptioncode='CT';
I don’t think I quite follow the semantics behind the ‘ANY’ keyword in predicates. I was able to get close with,
NSPredicate *pre = [NSPredicate predicateWithFormat:
@"order == %@ and
(any options.optionTypeCode == %@ and any options.optionCode == %@)
and
(any options.optionTypeCode == %@ and any options.optionCode == %@)",
order, @"OptionSet1", @"BT", @"OptionSet2", @"CT"];
But it also matched when the optionCodes where reversed.
I tried factoring the ‘ANY’ outside each parenthesis expression, but that caused a parse exception.
Perhaps a simpler example would be interesting as well. What if I have an Author entity with a to-many relationship to Books. How would I create a predicate to say, find the author who has written the both the book titled “Book1” and the book titled “Book2”?
Someone answered on Apple developer forum, https://devforums.apple.com/message/659752#659752
Repeating post here,
It sounds like what you’re looking for is a sub-query. One of the explanations for sub queries: http://funwithobjc.tumblr.com/post/2726166818/what-the-heck-is-subquery
I think it would be something like
for the predicate. Although I’m not sure why you had the order == %@ clause in your attempt, and I just kept it in the version with subqueries for consistency with that…