Issue with adding a one-to-one foreign-key connect

2019-08-20 01:56发布

问题:

I am trying to add a connection to a RestKit mapping but without success.

My JSON is as follows:

{
  parent: {
    token: "token"
    title: "title",
    description: "description",
    child_id: 1
  }
}

My CoreData scheme defines that the Parent ManagedObject has a Child relation under the child key (and the opposite). The Parent mapping happens after I already have a corresponding Child object in CoreData, so that's not a problem.

I followed some links and discussions around the web in order to solve this, but none work. What is the right way to do this, without having to add a child_id property to Parent (some people claimed they did this but it looks wrong to me).

Assuming I have this mapping:

- (RKEntityMapping *)parentResponseMapping {
    RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:@"Parent" inManagedObjectStore:[self myStore]];
    [mapping addAttributeMappingsFromArray:@[@"title", @"description"]];
    mapping.identificationAttributes = @[@"token"];
    return mapping;
}

At first I tried adding the connection like this:

NSEntityDescription *parentEntity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:[self myContext]];
NSRelationshipDescription *childRelationship = [parentEntity relationshipsByName][@"seller"];
RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:childRelationship keyPath:@"child_id"];

[mapping addConnection:connection];

But I got an error that child_id is not a valid attribute (this is where I tried adding the child_id property to my scheme but again, that seems messy to me, and besides, it didn't work).

I also tried adding the connection by:

[addConnectionForRelationship:@"child" connectedBy:@"child_id"]

But this didn't work either.

Both these methods ignore the child mapping anyway.

What is the right way to achieve this?

EDIT: RestKit Object Mapping relationships with foreign keys - This was answered here already but the solution looks odd to me. Is this the only way to do this?

回答1:

without having to add a child_id property to Parent (some people claimed they did this but it looks wrong to me).

This is actually the right way to do it...

The point is the RestKit needs some way to map the two items together, some key with which to search and find the items to connect. This information only needs to be transient (assuming you are loading the data in one go or the other side of the identification is a persistent attribute). There isn't really another way to do it.