There is an array of $catID .

Here are its meanings:

 array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } 

Trying to run it to save through foreach. Here is the code:

 public function actionCreate() { $model = new Serial(); $category = Category::find()->where('tags<>1')->all(); $catSerial = new CatSerial(); if ($model->load(Yii::$app->request->post())) { $post=Yii::$app->request->post(); $catID=$post['CatSerial']['id_cat']; $model->save(); foreach($catID as $cat){ $catSerial->id_cat=$cat; $catSerial->id_serial=$model->id; $catSerial->isNewRecord = true; $catSerial->save(); } return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, 'category' => $category, 'catSerial' => $catSerial ]); } } 

The problem is that save() processed once the last why? And how to make work twice.

  • And id_cat not autoincrement? can try $catSerial->id_cat = NULL ? either do not write at all $catSerial->id_cat=$cat - Alexey Shimansky
  • id_cat not auto increment this id from another table - Sergalas
  • see here the solution to stackoverflow.com/questions/452859/ ... the question is how to correctly make an activerecord request of this type INSERT INTO MyTable (Column1, Column2) VALUES (Value1, Value2), (Value1, Value2) - Sergalas
  • Well, as an option to use batchinsert yiiframework.com/doc-2.0 batchinsert ... forming a pre-array ..... besides, you can write such a request with a lot of values .... but also through DAO - Alexey Shimansky
  • @ AlekseyShimansky yes thanks Aleksey can issue an answer I will accept - Sergalas

2 answers 2

Try this. But, if you have a lot of records in the loop, then it is better to use alternatives, such as batchinsert , yes.

 foreach($catID as $cat){ $catSerial = new CatSerial(); $catSerial->id_cat=$cat; $catSerial->id_serial=$model->id; $catSerial->save(); } 

    Save () in the loop works not once but last. You can of course update but refer to the database in a loop, not the best option. It is best to use batchinsert I write this answer myself because
    @ Alexey Shimansky refused to make out the answer himself.