正如问题标题中提到的,由于某些原因,在检查sqlite数据库时,关系设置不正确。RestKit导入JSON不会设置关系
我正在导入两个资源(书籍和章节),每个资源都在一个一对多结构的JSON文件中。这是一个例子JSON:
books.json: [ { "id": 1, "number": 12345, "name": "Book 1" } ]
chapters.json: [ { "id": 1, "bookId": 1, "name": "Chapter 1" } ]
我已经设置了以下映射:
RKEntityMapping *bookMapping = [RKEntityMapping mappingForEntityForName:@"Book"
inManagedObjectStore:managedObjectStore];
bookMapping.identificationAttributes = @[ @"id" ];
[bookMapping addAttributeMappingsFromArray:[Book attributesArray]]; // [@"id", @"number", @"name"]
RKEntityMapping *chapterMapping = [RKEntityMapping mappingForEntityForName:@"Chapter"
inManagedObjectStore:managedObjectStore];
chapterMapping.identificationAttributes = @[ @"id" ];
[chapterMapping addAttributeMappingsFromArray:[Chapter attributesArray]]; // [@"id", @"bookId", @"name"]
,当然还有连接:
[chapterMapping addConnectionForRelationship:@"book" connectedBy:@{ @"bookId": @"id" }];
这里是导入两个JSON的一部分文件:
RKManagedObjectImporter *importer = [[RKManagedObjectImporter alloc] initWithManagedObjectModel:managedObjectStore.managedObjectModel storePath:path];
NSString *bookJsonPath = [NSString stringWithFormat:@"%@/%@/books.json", [self getDocumentsPath], @"seeds"];
[importer importObjectsFromItemAtPath:bookJsonPath
withMapping:bookMapping
keyPath:nil
error:&error];
// [[importer managedObjectContext] saveToPersistentStore:&error];
NSString *chapterJsonPath = [NSString stringWithFormat:@"%@/%@/chapters.json", [self getDocumentsPath], @"seeds"];
[importer importObjectsFromItemAtPath:chapterJsonPath
withMapping:chapterMapping
keyPath:nil
error:&error];
success = [importer finishImporting:&error];
if (success) {
[importer logSeedingInfo];
NSLog(@"Finished seeding!");
}
导入过程完全正常,但书籍外键列中的章节全部为NULL。日志还显示:
Caching instances of Entity 'Book' by attributes 'guid'
Imported 551 objects from file at path ... (books)
Caching instances of Entity 'Chapter' by attributes 'guid'
Imported 1908 objects from file at path ... (chapters)
Starting 1908 connection operations ...
A seed database has been generated
哪种指示它开始创建连接,但什么也没有发生。
更新14年12月15日: 的两个主要错误是:
- 我使用了保留关键字
id
为(而不是说)属性和 - 我有一个在我的外键映射中犯了一个愚蠢的错误!在章节中出现的外键是
book
,我的映射预期为bookId
。尴尬!我改变了服务器,正确地返回bookId
作为外键,现在它工作。
这种方式只有连接是足够的!无需添加RKRelationShipMappings。
谢谢你用'id'字段指出我的错误。我仔细检查了我的属性映射,并将其重命名为“guid”。现在它的工作! – codepushr 2014-12-13 17:34:59