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

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?

我认为动态模型创建或更新模型。
我假设我有一个这样的数组: p>

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

现在我想迭代该数组,并将数据写入模型,其中点符号告诉我必须写入关系。 p>

普通代码: p>

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

依此类推。 p>

我更喜欢更动态的方式: p>

  foreach($ data as $ key => $ value){
 $ properties = explode('。',$ key  ); 
 //现在困难的部分
 $ model [$ properties [0]] [$ properties [1]] = $ value; 
 //适用于发票 Address.city,
 //但不是对于first_name 
} 
  code>  pre> 
 
 

这是问题,我不知道爆炸会创建多少属性 。 有没有办法以动态的方式解决这个问题? p> div>

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);
}