In,yii2我想在一个表上插入sinlge行,在另一个表中插入多个具有相同id的行
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) {
$purchaseid = $modeld->purchaseid = $modelm->purchaseid;
$cid = $modeld->categoryid =$val['id'][$i];
$pc = $modeld->productcode = $val['pc'][$i];
$qty = $modeld->qty = $val['qty'][$i];
$remarks = $modeld->remarks = $modelm->remarks;
if($modeld->save()){
$i++;
}
}
"$modeld->save()" it saves only first entry.
答案 0 :(得分:2)
\yii\db\ActiveRecord
的{{3}}属性决定:
记录是否为新记录,应在调用
时插入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
...