douhui9192 2015-09-23 12:49
浏览 62

来自多维数组的雄辩质量分配以及模型关系

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).

Edit: security is not my concern at the moment, i will be sanitizing $_POST before inserting, but the main issue is mass assignment without having to know which class i'm using and assigning relationships by hand.

  • 写回答

1条回答 默认 最新

  • duanhe8280 2015-09-23 14:06
    关注

    It looks like you are missing the relationship between blog_post and author. If you have a relationship defined, you won't be able to save author because it will be missing a required foreign key.

    This might work:

    $parent = null;
    array_walk($_POST, function(value, key){
     if (is_array($value) && class_exists($key)) {
        $object = new $key($value);
        if(!empty($parent)){
         $parent->$key()->save($object); // function author(){$this->hasOne('author');} on blog_post model
        }
        else{
         $object->save();
        }
        $parent = $object;
     }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大