0

给定以下核心数据关系:

  • Recipe <<---> Cookbook
  • Recipe <<---> Author
  • Cookbook <<---> Author

而这个代表配方的源 JSON:

{
  "id": 123,
  "name": "Recipe Name",
  "author": {
    "id": 456,
    "name": "Author Name"
  },
  "cookbook": {
    "id": 789,
    "title": "Cookbook Title"
  }
}

我正在寻找一个 RestKit 映射,它会产生一个满足以下条件的配方:

  • recipe.cookbook IN recipe.author.cookbooks
  • recipe.cookbook.author === recipe.author

这是我到目前为止所拥有的:

recipeMapping = 
  [RKEntityMapping mappingForEntityForName:@"Recipe" inManagedObjectStore:_store];
[recipeMapping addAttributeMappingsFromDictionary:@{
   @"id": @"id",
   @"name": @"name"
}];
recipeMapping.identificationAttributes = @[@"id"];

RKEntityMapping *authorMapping = 
  [RKEntityMapping mappingForEntityForName:@"Author" inManagedObjectStore:_store];
[authorMapping addAttributeMappingsFromDictionary:@{
  @"id": @"id",
  @"name": @"name"
}];
authorMapping.identificationAttributes = @[@"id"];

RKEntityMapping *cookbookMapping = 
  [RKEntityMapping mappingForEntityForName:@"Cookbook" inManagedObjectStore:_store];
[cookbookMapping addAttributeMappingsFromDictionary:@{
  @"id": @"id",
  @"title": @"title"
}];
cookbookMapping.identificationAttributes = @[@"id"];

[recipeMapping 
  addRelationshipMappingWithSourceKeyPath:@"cookbook" 
                                  mapping:cookbookMapping];
[recipeMapping 
  addRelationshipMappingWithSourceKeyPath:@"author" 
                                  mapping:authorMapping];

// Now what?

应用此映射后,recipe.cookbook是 的正确实例Cookbook,并且recipe.author是 的正确实例Author,但当然recipe.cookbook.author是 nil 并且recipe.author.cookbooks是空的。

4

1 回答 1

0

由于您没有所需的信息,因此在映射时您无法真正做到这一点。

您可能能够设置使用外键的关系,而不是具有外键的特殊属性,而是使用 3 个对象之间的关系。我想说这有点脆弱,因为它依赖于映射期间处理关系的顺序。

相反,我会考虑在后处理期间(即在映射完成后的回调中或通过willSave在托管对象子类上实现)或在您实际需要了解关系时按需执行此操作。这可以使用 KVC 来完成,例如:

如果您执行 fetch 以获取所有作者,则可以使用以下方法为每个作者构建食谱:

author.cookbooks = [author.recipes valueForKeyPath:@"@distinctUnionOfObjects.cookbooks"];
于 2013-06-01T14:33:31.490 回答