CoreData 建模逆关系
Apple 的文档建议在 CoreData 中建模数据模型时使用逆关系。
我有以下示例:
一本书(实体)有几个“页面”和一个“封面”和一个“封底”。 页面(实体)位于一本“书”中(因此“书”是“页面”的反义词)。
到目前为止,这是标准情况...但是现在,我的问题是:
我只有一个类 Cover(实体)。封面(实体)位于一本“书”上。在这本“书”上,封面是“封面”或“封底”。因此,“书”的反义词是“frontCover”或“backCover”。
这无法在 CoreData 中建模。关系只能是一种关系的逆关系,但不能是这个或那个关系的逆关系。
对此进行建模的最佳方法是什么?单向关系(无逆关系)?
感谢您的回答, 克里斯
Apple's documentation suggests the use of inverse relationships when modelling data models in CoreData.
I have the following example:
A Book (Entity) has several "pages" and one "frontCover" and one "backCover".
A Page (Entity) is in one "book" (so "book" is the inverse of "pages").
OK so far, that's the standard case...BUT now, my problem:
I only have one class Cover (Entity). A Cover (Entity) is on one "book". On this "book" the Cover is EITHER the "frontCover" OR the "backCover". So, the inverse of "book" is EITHER "frontCover" OR "backCover".
This cannot be modelled in CoreData. A relationship can only be the inverse of one relationship, but not of EITHER this OR that relationship.
What is the best way to model this? Unidirectional relationships (no invers)?
Thanks for your answers,
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以做类似下面模型的事情(第一张图)。这将使 Cover 的逆关系为零。不过,这对我来说感觉不太对劲。
另一个选项(第二张图)是为 Book 提供一个引用 2 个 Cover 对象的“封面”关系,并为 Cover 提供一个 isFront 布尔属性。这将允许称为“书”的逆关系。
You could do something like the model below (first image). This would leaving of Cover's inverse relationships as nil. This doesn't feel right to me, though.
Another option (second image) would be to give Book a 'covers' relationship which references 2 Cover objects, and give Cover an isFront boolean attribute. This would allow for inverse relationship called 'book'.
一种方法是将 Cover 创建为具有两个子实体的“抽象”实体 - FrontCover 和 FrontCover。后盖。然后你就可以创建关系并建立关系。与其中每一个相反。
One way to do it could be to create Cover as an "abstract" entity with two sub entities - FrontCover & BackCover. Then you could create the relationship & inverse to each of those.
我只是想补充一下。
一种方法是拥有 2 个子实体。但只有当 FrontCover 和 BackCover 差异很大时,这才有用。
如果它们是完全相同的对象,您应该在实体中使用枚举。
该枚举区分封面是 frontCover 还是 BackCover。
然后,您从书籍到封面仅设置 1 个“对多”关系。
coredata 的目的是保存您的数据。无论如何,你的逻辑应该在代码中。
创建两个子实体本质上与 westSider 的答案相同。子实体只需在原始关系上添加另一种关系即可。
I just want to add.
One way is to have 2 subentities. But that's useful only if FrontCover and BackCover differs a lot.
If they are exactly the same object, you should instead use an enum in the entities.
That enum differentiate whether the cover is frontCover or BackCover.
Then you set only 1 "to many" relationship from book to cover.
The purpose of coredata is to save your data. Your logic should be in the code anyway.
Also creating two subEntities is essensially the same with westSider's answer. Sub entities simply add another relationship on the original one.