Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestKit one-to-many inverse relationships (without CoreData)

Setup

Imagine the following relationship between an Author and a Book:

[Author] -- has many --> [Book]

Using restkit, I have an Author model and a Book model, and I create the relationship between Author and Book like this:

[authorMapping hasMany:@"books" withMapping:booksMapping];

I can now access an Author's books through Author's property:

@property (strong, nonatomic) NSSet *books;

So far so good. Similarly, I'd like to access a Book's author through it's property:

@property (weak, nonatomic) Author *author;

Problem

This is where the problems start. To achieve this inverse relationship, I added the following:

[booksMapping hasOne:@"author" withMapping:authorMapping];

This results in each mapping recursively calling each other until the program dies. Not good at all. Inspecting the docs I find that hasOne/Many:withMapping: methods are simply calling mapKeyPath:toRelationShip:withMapping: so there's not really an alternative there. Furthermore, adding a mapping as the following:

[bookMapping mapKeyPath:@"author" toAttribute:@"author"];

Will, obviously, just create the mapping but not actually map the Author object to the Book's author property.


Question

How can I create an inverse one-to-many relationship between two or more models using RestKit, but not CoreData?

like image 653
Kasper Munck Avatar asked Oct 29 '12 20:10

Kasper Munck


1 Answers

Note: newer versions of restkit use a diffent mapping scheme.

Note2: I think in your example you mean:

[booksMapping hasOne:@"author" withMapping: authorMapping]; (not booksMapping)

The problem here is not the mapping, you shouldn't define the same mapping to the many-to-one side, this mapping is already done (defined in the authorMapping). You simply want a pointer to the parent item, not to repeat the whole mapping process.
The real problem is you'd need to define the parent object as a property of the child object, in terms of NSDictionaries, this might be possible using a custom category, but it's not something RestKit supports to be used to transformed objects.

like image 124
Kevin R Avatar answered Oct 12 '22 05:10

Kevin R