dongliling6336 2017-06-01 18:16
浏览 117
已采纳

Laravel迭代数组并写入带关系的模型

I think about dynamic model creation or updating an model.
Let's assume i have an array like this:

$data = array(
'first_name' => 'Max',
'last_name' => 'Power',
'invoiceAddress.city' => 'Berlin',
'invoiceAddress.country_code' => 'DE',
'user.status_code' => 'invited'
);

Now i would like to iterate that array, and write the data to an model, where the dot notation tells me that i must write to an relation.

Normal code:

$model->first_name = $data['first_name'];
$model->last_name = $data['last_name'];
$model->invoiceAddress->city = $data['invoiceAddress.city'];

and so on.

I would prefer a more dynamic way:

foreach($data as $key => $value){
  $properties = explode('.',$key);
  //Now the difficult part
  $model[$properties[0]][$properties[1]] = $value;
  //Would work for invoiceAddress.city,
  //but not for first_name
}

Here is the problem, that i don't know how many properties the explode will create. Is there a way to solve such problem in a dynamic way?

  • 写回答

1条回答 默认 最新

  • duanchu0031 2017-06-01 18:53
    关注

    You could use the Illuminate\Support\Arr helper from Laravel like this:

    foreach($data as $key => $value) {
        Arr::set($model, $key, $value);
    }
    

    It works because the Arr class uses dot notation to access the properties like:

    Arr::get($model, 'invoiceAddress.country_code');
    

    Is equivalent to:

    $model['invoiceAddress']['country_code'];
    

    If you prefer to use cleaner helper:

    foreach($data as $key => $value) {
        array_set($model, $key, $value);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?