MagicalRecord关系映射重复对象,尽管主键 [英] MagicalRecord relationship mapping duplicates objects despite primary keys
问题描述
我需要一些帮助,我遇到的MagicalRecord数据导入的问题。我的印象是,MagicalRecord能够处理关系映射,而不通过查看主键( relatedByAttribute
)重复对象。
I'm in need of some assistance for an issue I am experiencing with MagicalRecord data importing. I was under the impression that MagicalRecord was able to handle relationship mapping without duplicating objects by looking at the primary keys (relatedByAttribute
).
以下是一个简单的JSON:
Here's a simple JSON:
[
{
parentId: "<unique id>",
parentName : "<name>",
children : [
{
childId: "<unique id>",
childName: "<name>"
},
{
childId: "<unique id>",
childName: "<name>"
}
]
},
{ <another parent with children> }
]
我有一个NSManagedObject code>其与
Child
NSManagedObject具有一对多关系。关系名称是 children
,并且我在 Child $上设置了
relatedByAttribute
c $ c>和父
到 childId
和 parentId
。
I've got an NSManagedObject Parent
which has a to-many relationship with a Child
NSManagedObject. The relationship name is children
and I've set the relatedByAttribute
on the Child
and Parent
to childId
and parentId
respectively.
当我解析JSON时, Parent
不会重复,它会正确检查主键,现有对象(如果存在)。但是对于 Children
,每次解析JSON时都会复制对象。如果我单独解析 Children
(所以JSON只包含一个有子字典的数组),没有正确映射数据和使用
When I parse the JSON the Parent
is not duplicated and it correctly checks for the primary key and uses the existing object if present. However for the Children
it duplicates the objects every time I parse the JSON. If I parse the Children
individually (so JSON just contains an array with children dictionaries) it has no problem correctly mapping the data and using existing objects for Children
that already exist in the database.
我误解了并对MagicalRecord如何映射关系有错误的期望。目前我已经设置了一个扩展类'importChildren:`,我可以手动处理所有的查找并创建/导入对象。
Did I misunderstand and have the wrong expectations for how MagicalRecord maps relationships? Currently I've setup an extension class with 'importChildren:` where I can handle all the look-ups manually and create/import the objects accordingly.
谢谢! p>
Thanks!
推荐答案
我设法解决这个问题。
在 children
关系的用户信息字典中添加 relatedByAttribute
,对于 code>实体。
What I did was add relatedByAttribute
in the User Info dictionary for the children
relationship AND for the Child
entity as well.
因此,点击关系并将 relatedByAttribute
设置为 childId
(在上面的示例中),并且还单击左侧的Child实体,并且还将 relatedByAttribute
设置为<$ c $
So click on the relationship and set relatedByAttribute
to childId
(in my example above) and also click on the Child entity on the left and for this also set relatedByAttribute
to childId
in the User Info dictionary for the entity itself.
这允许Magical Record使用现有对象正确地映射或创建新的对象。需要 - 授予ID属性是100%唯一的!
This allows Magical Record to correctly map using existing objects or create new ones if needed - granted that the ID attribute is 100% unique!
这篇关于MagicalRecord关系映射重复对象,尽管主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!