Reputation: 889
Okay, so lets say I have an api, which returns a object of data in json. The object looks like the following.
{
"id" : 1,
"name":"SynAck",
"sex":"Male",
"age":34,
"roles": [
{
"id":1
"name":"user"
"assigned":"2013-06-10"
},
{
"id":1
"name":"admin"
"assigned":"2014-01-09"
}
],
"created":"2014-06-10"
}
As you can see there are 2 objects returned here namely, the first one, lets call it "user" and another object, which is an array inside the first, "roles". There are 2 roles assigned to the user.
So lets say I want to load this information up into my DB verbatim. I could create 3 tables, 'user' and 'roles' and 'user_roles', with foreign keys linking user->user_roles->roles. One user has many roles.
CREATE TABLE IF NOT EXISTS `users` (
`id` INT(12) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`sex` VARCHAR(10) NOT NULL,
`age` SMALLINT(2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `roles` (
`id` INT(12) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`assigned` DATETIME ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `user_roles` (
`user_id` INT(12) UNSIGNED NOT NULL ,
`role_id` INT(12) UNSIGNED NOT NULL ,
CONSTRAINT `fk_ur_user_id` FOREIGN KEY(`user_id`) REFERENCES users(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_ur_role_id` FOREIGN KEY(`role_id`) REFERENCES roles(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE `idx_user_id_role_id`(`user_id`, `role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
I would then use artisan to create the Eloquent models and in the user model, I would have a hasManyThrough('roles', 'user_roles');
What would be the quickest and cleanest way of loading the data from the json into the models/tables?
Would I just have to assign the values one by one, or is there a way to map the attributes from the json objects to the eloquent model? If this is possible, how does it handle the relations?
Upvotes: 0
Views: 1184
Reputation: 2644
I think that is possible to create the models for each table and then use the funcion json_decode
to convert the JSON to an array and then use Eloquent methods to save then. Raw example:
$data = json_decode($json);
User::create($data);
Still, you need to extract the relationship data. Raw example:
$data = json_decode($json);
$roles = $data['roles'];
unset($data['roles']);
$user = User::create($data);
$user->roles()->create($roles);
Upvotes: 2