Yii2使用actionCreate中的foreach循环在数据库中保存多个数据

时间:2022-10-05 10:07:58

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.

在我的项目中,我想使用foreach循环一次插入多行数据。我有一个包含元素数组的变量。

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.

例如,如果我的数组有3个不同的元素。我想在3个不同的db表行中保存所有这3个元素。我还有其他列对于所有3个数组元素都是相同的。

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

我把它们放在foreach语句中,但只保存了第一个元素。有什么办法可以实现吗?

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.

只有productline_id不同,其他列将具有所有prdouctline_id的相同数据。

Thank You!!!

3 个解决方案

#1


2  

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,
        ]);
    }
}

#2


0  

maybe you can modify my code

也许你可以修改我的代码

   public function actionCreate()
   {
       $model = new SemesterPendek();
      $model->user_id = \Yii::$app->user->identity->id;
      $model->npm = \Yii::$app->user->identity->username;


        $modelsNilai = [new Nilai];


       if ($model->load(Yii::$app->request->post())){
         $model->waktu_daftar = date('Y-m-d h:m:s');

         $model->save();

   $modelsNilai = Tabular::createMultiple(Nilai::classname());
           Tabular::loadMultiple($modelsNilai, Yii::$app->request->post());


           // validate all models
           $valid = $model->validate();
           $valid = Tabular::validateMultiple($modelsNilai) && $valid;

           if ($valid) {
               $transaction = \Yii::$app->db->beginTransaction();
               try {
                   if ($flag = $model->save(false)) {
                       foreach ($modelsNilai as $indexTools =>$modelNilai) {
                           $modelNilai->id_sp = $model->id;
                       //    $modelNilai->user_id = \Yii::$app->user->identity->id;

                           if (! ($flag = $modelNilai->save(false))) {
                               $transaction->rollBack();
                               break;
                           }
                       }
                   }
                   if ($flag) {
                       $transaction->commit();
                       return $this->redirect(['view', 'id' => $model->id]);
                   }
               } catch (Exception $e) {
                   $transaction->rollBack(); \Yii::$app->session->setFlash('error','gagal');
               }

       }

       } else {
           return $this->render('create', [
               'model' => $model,
                'modelsNilai' => (empty($modelsNilai)) ? [new Nilai] : $modelsNilai,



           ]);
       }
   }

#3


0  

You need to create a different object to save in different rows. For loop executes 3 times but every time same object is being updated. You can define new object and save each time. Below code will work

您需要创建另一个对象以保存在不同的行中。 For循环执行3次,但每次更新相同的对象。您可以定义新对象并每次保存。下面的代码将起作用

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,
            ]);
        }
    }

#1


2  

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,
        ]);
    }
}

#2


0  

maybe you can modify my code

也许你可以修改我的代码

   public function actionCreate()
   {
       $model = new SemesterPendek();
      $model->user_id = \Yii::$app->user->identity->id;
      $model->npm = \Yii::$app->user->identity->username;


        $modelsNilai = [new Nilai];


       if ($model->load(Yii::$app->request->post())){
         $model->waktu_daftar = date('Y-m-d h:m:s');

         $model->save();

   $modelsNilai = Tabular::createMultiple(Nilai::classname());
           Tabular::loadMultiple($modelsNilai, Yii::$app->request->post());


           // validate all models
           $valid = $model->validate();
           $valid = Tabular::validateMultiple($modelsNilai) && $valid;

           if ($valid) {
               $transaction = \Yii::$app->db->beginTransaction();
               try {
                   if ($flag = $model->save(false)) {
                       foreach ($modelsNilai as $indexTools =>$modelNilai) {
                           $modelNilai->id_sp = $model->id;
                       //    $modelNilai->user_id = \Yii::$app->user->identity->id;

                           if (! ($flag = $modelNilai->save(false))) {
                               $transaction->rollBack();
                               break;
                           }
                       }
                   }
                   if ($flag) {
                       $transaction->commit();
                       return $this->redirect(['view', 'id' => $model->id]);
                   }
               } catch (Exception $e) {
                   $transaction->rollBack(); \Yii::$app->session->setFlash('error','gagal');
               }

       }

       } else {
           return $this->render('create', [
               'model' => $model,
                'modelsNilai' => (empty($modelsNilai)) ? [new Nilai] : $modelsNilai,



           ]);
       }
   }

#3


0  

You need to create a different object to save in different rows. For loop executes 3 times but every time same object is being updated. You can define new object and save each time. Below code will work

您需要创建另一个对象以保存在不同的行中。 For循环执行3次,但每次更新相同的对象。您可以定义新对象并每次保存。下面的代码将起作用

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,
            ]);
        }
    }