0
votes

We're using RestKit to cache data from a remote web-service, similar to Stackoverflows API.

In the API has questions and tags, but instead of getting the tag in text we get the tag id.

The questions resource looks like this:

{
  "items": [
    {
      "question_id": 11260172,
      "tags": [
          { "tag_id" : 1},
          { "tag_id" : 2},
          { "tag_id" : 3}
      ],
      "view_count": 1,
      [...]
}

The tags resource looks like this:

{
  "items": [
    {
      "id": 1,
      "name": "c#",
    },
    {
      "id": 2,
      "name": "java",
    },
    {
      "id": 3,
      "name": "php",
    }]
}

We would like to create a join table between questions and tags, so that the question can have many tags and the tag has many questions.

We have got one to many working but not the join table many to many. We therefore wonder how the RestKit many to many mapping should look for a relationship like this, and how the data model should look.

We have tried the following mapping, but it isn't many-to-many.

[tagMapping mapKeyPath:@"id" toRelationship:@"questions" withMapping:tagsQuestionsMappingMapping];
[questionMapping mapKeyPath:@"tags" toRelationship:@"tags" withMapping:tagsQuestionsMappingMapping];
1

1 Answers

1
votes

Just so we are clear. Because your root key is the same in these two different web services, you need to use two different maps.

Here is an example mapping for your questions endpoint:

RKManagedObjectMapping* nested = [RKManagedObjectMapping mappingForClass: [NSDictionary class] inManagedObjectStore:nil];
[nested mapKeyPath: @"tag_id" toAttribute: @"id"];

RKManagedObjectMapping* questions = [RKManagedObjectMapping mappingForClass: [NSDictionary class] inManagedObjectStore: nil];
[questions mapAttributes: @"question_id", @"view_count", nil];  //I don't know your core data model...
[questions hasMany: @"tags" withMapping: nested];
[questions connectRelationship: @"tags" withObjectForPrimaryKeyAttribute: @"tag_id"];

And here is an example mapping for your tags endpoint

RKManagedObjectMapping* tags = [RKManagedObjectMapping mappingForClass: [Tag class] inManagedObjectStore: store];
[tags mapAttributes: @"id", @"name", nil];

Notice:

1) The tag map is different each time because the primary key attribute name is different in each feed

2) I don't know your core data topography so these maps probably won't work as they are. You are going to need to understand what I am doing and redo it for your application.

3) You never worry about the join table. This is handled by the frameworks.