Yii2 从 CheckBoxList 插入数据

Yii2 insert data from CheckBoxList

在我的表格中:

 <?= GridView::widget([
 'id' => 'griditems',
 'dataProvider' => $dataProvider,
  'columns' => [
   'receiver_name',
   'receiver_phone',
   'item_price',
   'shipment_price',
   ['class' => 'yii\grid\CheckboxColumn'],
  ],

]); ?>

在我的控制器中:

public function actionCreate()
{
    $model = new Package();
    $searchModel = new ShipmentSearch();
    $searchModel->shipment_position=1; // الشحنه في مقر الشركة
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    if ($model->loadAll(Yii::$app->request->post())){ 
        $select = Yii::$app->request->post('selection');

        foreach($select as $id){
            $shipment= shipment::findOne((int)$id);
            $model->company_id=1;
            $model->shipment_id=$shipment->id;
            $model->send_from=$shipment->send_from;
            $model->send_to=$shipment->send_to;
            $model->save(false);

        }
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
            'dataProvider'=>$dataProvider,
        ]);
    }
}

我只是尝试用这种方式插入数据,但插入的数据只是列表中的最后一个或最后一个 CheckBox。我试着打印 foreach 中的 id 并且有多个 id.

那是因为您在 foreach 中为每个 save() 重复使用同一个实例,所以您一遍又一遍地覆盖同一个模型。您需要将 $model = new Package() 放在 foreach 中:

foreach($select as $id){
    $shipment= shipment::findOne((int)$id);
    $model = new Package();
    $model->company_id=1;
    $model->shipment_id=$shipment->id;
    $model->send_from=$shipment->send_from;
    $model->send_to=$shipment->send_to;
    $model->save(false);
}