I've got a multidimensional array coming from $_POST. Its keys are exactly the same as either columns in the blog_posts table or names of its relations (e.g. author).
I would like to mass assign the $_POST to a matching object and its relations. Example:
$_POST = array (
'blog_post' => array (
'title' => 'the title of the post',
'content' => 'the content of the post',
'date' => '23-09-2015',
'author' => array (
'name' => 'hydra',
'age' => 47,
'location' => 'Russia',
),
),
);
would be mapped to a blog_post object and a author object.
2 things to keep in mind:
- this is only an example, i've no clue what type of objects i'll be working with;
- the solution should also be usable with collections of objects
my current (obviously non-working) solution would involve:
array_walk($_POST, function(value, key){
if (is_array($value) && class_exists($key)) {
$object = new $key($value);
$object->save();
}
});
This only saves the first object (blog_post).
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire