Hello, I have a User table and UserPhone table. One user may have multiple number. user_phone - user_id, phone Communication 1 to 1 How to do when adding a user, several fields of type <?= $form->field($userPhone, 'phone') ?> What does this require to change something in the controller?

  • Communication in this case should be one to many. One user, several phones. - Samuel Loog

1 answer 1

Use an array

 <?= $form->field($userPhone, 'phone[]') ?> 

Example action:

 $transaction = Yii::$app->db->beginTransaction(); try { $model->load(Yii::$app->request->post()); foreach($model->phone as $phone){ $userPhone = new UserPhone(); $userPhone->phone = $model->id; if($userPhone->valid()){ $this->link('userPhone', $userPhone); } } ... $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); } 

An example is not true. Read about the options for maintaining links, and choose for yourself and your implementation yours.