Search code examples
arraysdatabaseforeachyii2controllers

Yii2 Save multiple data in the db using foreach loop in actionCreate


In my project I want to insert multiple rows of data at a single time using the foreach loop. I have a variable which has array of elements.

For instance if my array has say 3 different elements. I want to save all these 3 elements in the 3 different db table rows. I also have other columns which are same for all the 3 array elements.

I have put them inside foreach statement but only the 1st elements gets saved. Is there any method I can achieve this?

My code

public function actionCreate($prodID)
    {
        $model = new ProductlinesStorage();

        if ($model->load(Yii::$app->request->post())) {
           $productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();

           foreach ($productlineID as $singleProductlineID) {
                $model->productline_id = $singleProductlineID->productline_id;
                $model->user_id = Yii::$app->user->identity->user_id;
                $model->isNewRecord = true;
                $model->save();  
            }  
            return $this->redirect(['/product/storage?id='.$prodID]);
        } else {
            return $this->renderAjax('create', [
                'model' => $model,
                'prodID' => $prodID,
            ]);
        }
    }

Only the productline_id is different other columns will have same data for all the prdouctline_id.

Thank You!!!


Solution

  • You have only one model object, and you are saving only to it. Try this:

    public function actionCreate($prodID)
    {
        $model = new ProductlinesStorage();
    
        if ($model->load(Yii::$app->request->post())) {
           $productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
    
           foreach ($productlineID as $singleProductlineID) {
                $model = new ProductlinesStorage();
                $model->productline_id = $singleProductlineID->productline_id;
                $model->user_id = Yii::$app->user->identity->user_id;
                $model->isNewRecord = true;
                $model->save();  
            }  
            return $this->redirect(['/product/storage?id='.$prodID]);
        } else {
            return $this->renderAjax('create', [
                'model' => $model,
                'prodID' => $prodID,
            ]);
        }
    }