Yii2 - 初始化具有数组值的模型

时间:2017-09-09 17:42:41

标签: php arrays yii yii2

如何创建一个具有另一个数组默认值的模型。

我的意思是,如果我有这样的数组:

[
0 => [
    'remarks' => 'ACETONE - '
    'material' => '70.00'
]
1 => [
    'remarks' => 'Leak Test 1 Bar'
    'material' => '13.50'
]
2 => [
    'remarks' => 'Foot Valve Incapsulated O-Ring 1 pcs - Replace'
    'material' => '6.70'
]
3 => [
    'remarks' => 'Seal Teflon 3\" Bottom Valve - Replace'
    'material' => '10.50'
]
4 => [
    'remarks' => 'Gasket Carton Bottom Valve 4 Hole 2 pcs - Replace'
    'material' => '14.60'
]
]

你知道,该模型只存储一个默认值:

$modelJobOrderDetails =[new JobOrderDetail([
                'remarks' => ?? get from array above
                'material' => ?? get from array above
            ])] ;

如何将这些数组存储到此模型中? 请指教。

2 个答案:

答案 0 :(得分:1)

假设你有

 $myArray =    [
      0 => [
          'remarks' => 'ACETONE - '
          'material' => '70.00'
      ]
      1 => [
          'remarks' => 'Leak Test 1 Bar'
          'material' => '13.50'
      ]
      2 => [
          'remarks' => 'Foot Valve Incapsulated O-Ring 1 pcs - Replace'
          'material' => '6.70'
      ]
      3 => [
          'remarks' => 'Seal Teflon 3\" Bottom Valve - Replace'
          'material' => '10.50'
      ]
      4 => [
          'remarks' => 'Gasket Carton Bottom Valve 4 Hole 2 pcs - Replace'
          'material' => '14.60'
      ]
    ];

你可以使用模型属性

在你的阵列上迭代一个poplulatin
  foreach($mymodel as $key = $value)        {
      $models[$key] = new JobOrderDetail();
      $models[$key]->attributes = $value;

  } 

http://www.yiiframework.com/doc-2.0/guide-structure-models.html#massive-assignment

答案 1 :(得分:0)

请阅读:http://www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail

$model = new JobOrderDetail();
$model->load($arrayData, ''); // '' = formname or empty string

这样,您可以确保只加载所需的(安全)属性。 $ arrayData是ONE模型的键/值对数组。你必须自己迭代。