Note that there are some explanatory texts on larger screens.

plurals
  1. PORetrieve Core Data object with specific relationship to two child objects
    primarykey
    data
    text
    <p>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? </p> <p>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).</p> <p>The issue is how to distinguish the first OrderItemOption object and the second in the query.</p> <p>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?</p> <p>The sql statement is:</p> <pre><code> 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'; </code></pre> <p>I don't think I quite follow the semantics behind the 'ANY' keyword in predicates. I was able to get close with, </p> <pre><code>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"]; </code></pre> <p>But it also matched when the optionCodes where reversed.</p> <p>I tried factoring the 'ANY' outside each parenthesis expression, but that caused a parse exception.</p> <p>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"?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload