iOS iPhone 获取一对多实体
基本上我有一个包含食物的实体和另一个包含酒的实体。每道菜都有推荐的酒。我需要能够选择一道菜并查看该菜品附带的葡萄酒推荐。不同的菜肴可以推荐相同的酒。
通常在 SQL 中我会创建一个链接表来实现这一点,但我在这里有点困惑,有人可以帮忙吗?
Basically I have an entity that contains food dishes and another that contains wine. Each dish has wine recommendations. I need to be able to select a dish and see the wine recommendations that come with that dish. Different dishes can have the same wine recommended for it.
Normally in SQL I would create a link table to achieve this but I am a bit stumped here, can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
核心数据在幕后为您处理“对多”关系的细节,您不需要创建中间表。
打开核心数据 .xcdatamodel 文件,选择
Food
实体,然后单击添加关系
。将关系命名为wines
。使其目标实体成为Wine
实体。打开数据模型检查器
(option-cmd-3) 并选择对多关系
。现在选择
Wine
实体。创建一个名为foods
的关系。在数据模型检查器
中将关系的Desination
设置为Food
实体,它的逆关系是wines
并将其设置为也是一个对多关系
。现在,
Food
的每个实例可以有许多Wine
,而Wine
的每个实例可以有许多Food
。Core Data handles the details of "to-many" relationships under the hood for you, you don't need to make intermediary tables.
Open your Core Data .xcdatamodel file, select the
Food
Entity, and clickAdd Relationship
. Name the relationshipwines
. Make its destination entity theWine
entity. Open theData Model Inspector
(option-cmd-3) and selectTo-Many Relationship
.Now select the
Wine
entity. Create a relationship calledfoods
. In theData Model Inspector
make the relationship'sDesination
theFood
entity, it's inverse relationship iswines
and set it to be aTo-Many Relationship
as well.Now each instance of
Food
can have manyWine
s and each instance ofWine
can have manyFood
s.如果您使用 Core Data,那么您可以简单地在数据库中创建一个 Wine 表,并使用它的主键作为 food-dishs 表中的外键。这个设计中什么不起作用?
If you are using Core Data, then you can simply create a Wine table in the database and use it's primary key as the foreign-key in the food-dishes table. What is not working in this design?