2017-09-09 35 views
0

如何创建一个模型,该模型具有另一个数组的默认值。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 
      ])] ; 

怎么样对这些数组存储到该模型? 请指教。

回答

0

假设你有

$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