Reputation: 27133
I have questions with relationships. I have to NSManagedObject classes Team and Player. Team can contain many players. Player can contain only one team.
Here is the JSON from the two requests:
/team
{
"id" : 1,
"name" : "Chicago Bulls",
"city" : "Chicago"
},
{
"id" : 2,
"name" : "Detroit Pistons",
"city" : "Detroit"
},
...
/players
{
"id" : 1,
"name" : "D.J. Augustin",
"teamId" : 1
},
{
"id" : 2,
"name" : "Carlos Boozer",
"teamId" : 1
},
...
Setup xcdatamodeld entities
Team Entity
atribute | mappedKeyName |
name | name |
teamID | id |
city | city |
Player Entity
atribute | mappedKeyName |
name | name |
playerID | id |
As you can see I have no set teamId there for Player entity, because we need to use relatedByAttribute key. First problem here I don't know for which property, attribute or a relationship I need to set relatedByAttribute key in User Info.
WRITE CODE PART
Suppose I already got team JSON represented by NSDictionary. What I do:
This code blow import all data from NSDictionary using User Info for each attribute for the Team entity. On this step everything is going fine.
Team *team = [Team MR_createEntity];
[team MR_importValuesForKeysWithObject:dictionary];
The second operation is get all players and attach them to the concrete team that already created on the first step using key teamId that you can see in JSON.
What I do on this step. Let suppose I got NSDictionary with first player.
The code is the same for this.
Player *player = [Player MR_createEntity];
[player MR_importValuesForKeysWithObject:dictionary];
But the relationships will no work, and MagicalRecords will no connect my player with the concrete team, because I have not set relatedByAttribute key as I said. I really need to help with this, because I understand the basic idea of import but can't understand where I need to set relatedByAttribute key I mean for which entity and for which attribute.
I saw also some duplicated issues with entities as well here on stack overflow, I think it is another question, but if you can suggest something it will be good, because I start from scratch and can make my code easy for understanding and without additional issues. Thank you a lot!
The link I use: magical import
Upvotes: 1
Views: 2962
Reputation: 14886
Have a look at this answer I posted for another question similar to yours:
Magical Record import (next step)
Upvotes: 0
Reputation: 27133
I solved this problem one thing I miss was mappedKeyName for the Relationship's user info.
At first we need to set mappedKeyName for the relationship that corresponds to the JSON key.
So in case if JSON you got looks like below:
{
"status": 1,
"message": "success",
"player": {
"playerID": 1,
"teamID": 14,
"firstname": "NAME",
}
}
mappedKeyName key will be player.teamID
relatedByAttribute key will be teamID that is an attribute of the Team entity.
Hope it helps someone.
Upvotes: 3