核心数据查找表
如何使用 Core Data 为可变查找表建模?
假设我有一张名为“绘画”的桌子。每幅画可以有一种或几种“颜色”,例如“红色”、“蓝色”等。因此“颜色”表是共享的。
我该如何建模?
我希望能够通过添加或删除颜色来修改“颜色”表。
How can I model a mutable lookup table using Core Data?
Say I have a table called "Paintings". Each painting can have one or several "Colors", such as "red", "blue", etc. The "Colors" table is therefore shared.
How can I model this?
I want to be able to modify the "Colors" table as well by adding or deleting colors as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望能够从一种颜色遍历所有使用该颜色的Painting对象,那么您需要使用多对Painting-->> ;具有一对多逆关系的颜色颜色-->>绘画。这似乎可能就是您正在寻找的东西。
另一方面,如果您不需要从“颜色”遍历到“绘画”,那么这可能是您想要放弃反向关系而只需要多绘画-->>“颜色”的罕见情况之一。
编辑
如果您希望能够删除绘画引用的颜色,那么您可能希望保持这两个实体之间的反向关系。此外,您还需要在 Color-->>Painting 和 Painting-->>Color 关系上定义“删除规则”。在这两种情况下,“无效”似乎是最好的选择。因此,当删除某种颜色时,所有引用该颜色的绘画都会简单地使该引用无效(删除)。同样,当一幅画被删除时,引用它的所有颜色都将停止引用它。
换句话说,应该不需要检查查找失败。也就是说,防御性编码始终是一个好习惯。
If you want to be able to traverse from a Color to all the Painting objects that use that color, then you would want to use to-many Painting-->>Color with to-many inverse relationship Color-->>Painting. This seems likely to be what you are looking for.
If, on the other hand, you do not need to traverse from Color to Painting, then this may be one of those rare cases where you would want to forego an inverse relationship and simply have to-many Painting-->>Color.
edit
If you want to be able to delete Colors that are references by Paintings, then you probably want to keep inverse relationships between these two entities. Furthermore, you will want to define 'delete rules' on the Color-->>Painting and on the Painting-->>Color relationships. In both cases, "nullify" seems the best choice. So, when a color is deleted, all paintings that reference it will simply have that reference nullified (removed). Likewise, when a painting is deleted, all colors that referenced it will cease to reference it.
In other words, there should be no need to check for lookup failures. That said, it is always good practice to code defensively.
是的,多对多关系是对此进行建模的正确方法。
Yes, a many-to-many relation is the correct way to model this.
你需要一个像这样的数据模型:
You need a data model something like this: