[英]CoreData, many-to-many relationships and NSPredicate
I have a CoreData datamodel that includes a many-to-many relationship. 我有一个包含多对多关系的CoreData数据模型。 As it turns out NSPredicate does not support many-to-many relationships.
事实证明,NSPredicate不支持多对多关系。 From CoreData.pdf: "You can only have one to-many element in a keypath in a predicate."
来自CoreData.pdf:“在谓词中的密钥路径中只能有一对多元素。”
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? CoreData是个坏主意我应该回到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: 创建一个新的RecipeIngredient实体,以便:
Recipe has many RecipeIngredients. 食谱有许多RecipeIngredients。
Ingredients has many RecipeIngredients. 成分有许多食谱成分。
A RecipeIngredient has one Recipe and one Ingredient. RecipeIngredient有一个食谱和一个成分。
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
你只是不能像
A <<-->> B <<-->> C
那样进一步查询
The predicate I used (in a model with Story <<-->> Team
) was this... 我使用的谓词(在
Story <<-->> Team
的模型中)就是这个......
[NSPredicate predicateWithFormat:@"SUBQUERY( teams, $t, $t IN %@ ).@count > 0", teams)];
This predicate is used in a fetch request against the Story entity. 此谓词用于针对Story实体的获取请求。 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)."
SUBQUERY格式对我来说有点混乱,所以我会注意到它可以被解读为“对于当前故事的团队集合中的每个团队,看看它是否在其他集合(团队)中。”
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.