user1170896
user1170896

Reputation: 739

RestKit Foreign Key Connections to-many and to-one

My goal is to implement one-to-many and many-to-one relationship connection with RestKit. I'm using version 0.20pre6. This page http://restkit.org/api/0.20.0/Classes/RKConnectionDescription.html#overview reports half example. First example is many-to-one. json:

{ "project": 
    { "id": 12345, 
      "name": "My Project",
      "userID": 1
    }
}

code:

NSEntityDescription *projectEntity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:managedObjectContext];
NSRelationshipDescription *userRelationship = [projectEntity relationshipsByName][@"user"];
RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:userRelationship attributes:@{ @"userID": @"userID" }];

The thing i missed during my first attempt is that userID needs to be in the Entity too. Otherwise it won't work. I don't really understand why... anyway it works.

My problem is related to the second example which is a one-to-many. Json example:

 { "project":
    {   "id": 12345,
        "name": "My Project",
        "userID": 1,
        "teamMemberIDs": [1, 2, 3, 4]
    }
 }

code:

 NSEntityDescription *projectEntity = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:managedObjectContext];
 NSRelationshipDescription *teamMembers = [projectEntity relationshipsByName][@"teamMembers"]; // To many relationship for the `User` entity
 RKConnectionDescription *connection = [[RKConnectionDescription alloc] initWithRelationship:teamMembers attributes:@{ @"teamMemberIDs": @"userID" }];

Now... teamMemberIDs needs to be in the Entity definition just like userID in the previous example. Here are my questions:

  1. How do I define teamMemberIDs since it's an array of values?
  2. Is there a working example about this things?? The examples directory inside RestKit library only shows nested relationships.
  3. Am I doing right? Am I missing something big?

Upvotes: 0

Views: 933

Answers (1)

Chris Vanderschuere
Chris Vanderschuere

Reputation: 78

I was struggling with this exact same problem, but was eventually able to find solution. Hopefully this will help you out.

Using the example:

  1. You must have an NSArray property of Project, your NSManagedObject, where you can map the teamMemberIDs to. To do this you make a transformable property.
  2. Map teamMemberIDs to that property as you would a primitive.
  3. Create a connectionDescription just as done in the example.

Upvotes: 4

Related Questions