使用RestKit进行外键关系映射 [英] Foreign key relationship mapping with RestKit
问题描述
我对RestKit完全不熟悉并且在某种程度上挣扎。
I'm totally new to RestKit and am struggling somewhat.
JSON:
{
"teams": [
{
"id": 1,
"name": "Team A"
},
{
"id": 2,
"name": "Team B"
}
],
"users": [
{
"id": 1,
"name": "cameron",
"teamId": 1
},
{
"id": 2,
"name": "paul",
"teamId": 2
}
]
}
CoreData:
@interface Team : NSManagedObject
@property (nonatomic, retain) NSNumber * teamId;
@property (nonatomic, retain) NSString * name;
@end
@interface User : NSManagedObject
@property (nonatomic, retain) NSNumber * userId;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Team * team;
@end
我的应用程序逻辑如下所示:
My application logic looks like this:
// team mapping
RKEntityMapping *teamMapping = [RKEntityMapping mappingForEntityForName:@"Team" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
teamMapping.identificationAttributes = @[@"teamId"];
[teamMapping addAttributeMappingsFromDictionary:@{
@"id": @"teamId",
@"name": @"name"
}];
// Register our mappings with the provider
RKResponseDescriptor *teamResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:teamMapping
pathPattern:nil
keyPath:@"teams"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self.objectManager addResponseDescriptor:teamResponseDescriptor];
// user mapping
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:[RKManagedObjectStore defaultStore]];
userMapping.identificationAttributes = @[@"userId"];
[userMapping addAttributeMappingsFromDictionary:@{
@"id": @"userId",
@"name": @"name"
}];
// Register our mappings with the provider
RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
pathPattern:nil
keyPath:@"users"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self.objectManager addResponseDescriptor:userResponseDescriptor];
我不能为我的生活找出如何让RestKit填充团队的财产用户对象。
I can't for the life of me work out how to get RestKit to populate the team Property of the user objects.
我看了很多帖子,但我尝试的都没有,这不是一般的用例吗?
I've look at so many posts but nothing I try works, is this not a usual use case?
有谁知道怎么做,非常感谢帮助!
Does anyone know how to do this, help would be very appreciated!
谢谢。
推荐答案
您需要在用户
实体中添加一个瞬态属性,该实体包含相关的 teamId
。这需要添加到您的 userMapping
。
You need to add a transient attribute to your User
entity which holds the associated teamId
. This needs to be added to your userMapping
.
然后,您需要为<$添加关系定义c $ c> userMapping :
[userMapping addConnectionForRelationship:@"team" connectedBy:@{ @"teamId": @"teamId" }];
这为RestKit提供了建立连接所需的信息,并指示它作为连接的一部分进行连接映射操作。
This gives RestKit the information it needs to make the connection and instructs it to make the connection as part of the mapping operation.
这篇关于使用RestKit进行外键关系映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!