2017-04-13 33 views
0

在,yii2我要插入一個表上的單層排以及具有相同ID的多個行中另一臺在,yii2我要插入一個表上的單層排以及多排在另一個表

controller code -- 
 

 
$modelcid = $modeld->categoryid; 
 
$modelpc = $modeld->productcode; 
 
$modelqty = $modeld->qty; 
 
$arrayvalue[]= array('id'=>$modelcid,'pc'=>$modelpc,'qty'=>$modelqty); 
 
$i=0; 
 
foreach($arrayvalue as $key=>$val) { 
 
\t $purchaseid = $modeld->purchaseid = $modelm->purchaseid; 
 
\t $cid = $modeld->categoryid =$val['id'][$i]; 
 
\t $pc = $modeld->productcode = $val['pc'][$i]; 
 
\t $qty = $modeld->qty = $val['qty'][$i]; 
 
\t $remarks = $modeld->remarks = $modelm->remarks; 
 
\t if($modeld->save()){ 
 
\t \t \t $i++; 
 
\t \t } 
 
\t } 
 

 
"$modeld->save()" it saves only first entry.

回答

2

\yii\db\ActiveRecord的的isNewRecord屬性確定:

是否該記錄是新的,應被插入時調用save()

當一個新的記錄被保存,這個變量被設置爲false所以你的代碼是建立在循環的第一次運行記錄,並在隨後的運行中進行更新。

您需要爲每個要保存的記錄明確設置該變量爲true。您還需要取消您的主鍵字段:

foreach ($arrayvalue as $key => $val) { 
    $modeld->isNewRecord = true; 
    unset($modeld->id); //assuming `id` is your primary key field 
    ... 

或者,也可以在循環使用的$modeld新實例:

foreach ($arrayvalue as $key => $val) { 
    $modeld = new ModelD; //assuming your model class is ModelD 
    ... 
相關問題