简体   繁体   中英

CoreData, many-to-many relationships and NSPredicate

I have a CoreData datamodel that includes a many-to-many relationship. As it turns out NSPredicate does not support many-to-many relationships. From CoreData.pdf: "You can only have one to-many element in a keypath in a predicate."

As a Recipe example: Many recipes and many ingredients. A recipe can have many ingredients of which "salt" can be one, while "salt" is used in many recipes. This is a natural many-to-many relationship.

What are suggested work-arounds?
Was CoreData a bad idea and I should go back to SQLite?

My understanding is that you can make any many-to-many relationship into separate one-to-many relationships by adding an intermediate entity.

You have:
Recipe has many Ingredients.
Ingredient has many Recipes.

Create a new RecipeIngredient entity such that:
Recipe has many RecipeIngredients.
Ingredients has many RecipeIngredients.
A RecipeIngredient has one Recipe and one Ingredient.

This question actually led me down the wrong path with a problem I was having. It turns out you can query a many-to-many relationship with a predicate. You just can't query further down like A <<-->> B <<-->> C

The predicate I used (in a model with Story <<-->> Team ) was this...

[NSPredicate predicateWithFormat:@"SUBQUERY( teams, $t, $t IN %@ ).@count > 0", teams)];

This predicate is used in a fetch request against the Story entity. The second "teams" is a set or array of teams I am searching for stories about. The SUBQUERY format is a bit confusing to me, so I'll note it can be read as, "For each team t in the current story's teams collection, see if it is in this other collection (teams)."

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM