【问题标题】:Laravel iterate array and write to Model with RelationsLaravel 迭代数组并写入具有关系的模型
【发布时间】:2017-11-03 00:16:24
【问题描述】:

我考虑创建动态模型或更新模型。
假设我有一个这样的数组:

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

现在我想迭代该数组,并将数据写入模型,其中点表示法告诉我必须写入关系。

普通代码:

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

等等。

我更喜欢动态的方式:

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
}

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

【问题讨论】:

    标签: php arrays laravel eloquent


    【解决方案1】:

    你可以像这样使用 Laravel 的 Illuminate\Support\Arr 助手:

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

    之所以有效,是因为Arr 类使用点符号来访问以下属性:

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

    相当于:

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

    如果您更喜欢使用更清洁的助手:

    foreach($data as $key => $value) {
        array_set($model, $key, $value);
    }
    

    【讨论】:

    • 先生,您真是个天才!它完全按照我想要的方式工作。谢谢你:)
    【解决方案2】:

    你也可以使用这些 Laravel 助手 data_fill()data_set()

    here 列出了其他 doted notation 函数。

    【讨论】:

      猜你喜欢
      • 2018-08-09
      • 1970-01-01
      • 2016-08-20
      • 2015-11-12
      • 2013-12-20
      • 2021-07-19
      • 2018-03-01
      • 1970-01-01
      相关资源
      最近更新 更多