2016-03-20 31 views
0

我想做一个清单供用户检查多个选项。然后,当它保存时,清单中的值转到“服务”表中,其他详细信息转到“后”表中。 如何从一个窗体插入多个记录到其他表。我被困在这里,我真的需要帮助。Yii2插入多个记录到其他表格

我创建功能:

public function actionCreate() 
{ 
    $model = new Posts(); 
    if ($model->load(Yii::$app->request->post()) && $model->save()) { 

     return $this->redirect(['category/index']); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 

我的形式:

<div class="col-lg-5"> 
     <?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?> 
      <?= $form->field($model, 'name') ?> 
      <?= $form->field($model, 'address') ?> 
      <?= $form->field($model, 'phone') ?> 
      <?= $form->field($model, 'price') ?> 
      <?= $form->field($model, 'square') ?> 
      <?= $form->field($model, 'content')->textarea() ?> 
      <?= $form->field($model, 'services_id[]')->checkboxList($items2) ?> 
+0

你的问题很混乱。您想要将'services_id'的多行保存在'services'表中,并将其他详细信息(名称,地址等)的单行保存到'post'表中。那是ryt吗?两个表之间的任何连接? –

+0

也显示你的帖子模型请 – scaisEdge

+0

创建两个模型并传递给表单中的行为'$ services = new Services();返回$ this-> render('create',[ 'model'=> $ model,'services'=> $ services ]);'并在表单中使用'字段($ services,'services_id []') - > checkboxList($ items2)?>' –

回答

1

如果你有两个型号为

服务,并张贴

下面给出的是我做了

我_form.php这个

它包含两个型号

1 $模型登录详细信息。 2. $ condact获取联系方式。

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> 
    <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?> 
    <?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?> 
    <?= $form->field($condact, 'name') ->textInput(['maxlength' => true]) ?> 
    <?= $form->field($condact, 'address')->textArea(['rows' => '6']) ?> 

我控制器

LogindetailsController.php

public function actionCreate() 
{ 
    $model = new Logindetails(); 
    $condact= new Condactdetails(); 

    if ($model->load(Yii::$app->request->post()) && $condact->load(Yii::$app->request->post())) { 
     $model->save(); 
     $condact->logid = $model->logid; 
     if($condact->save()){ 
      return $this->redirect(['view', 'id' => $model->logid]); 
     } 

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

这样,我必须插入到多个表。 我认为这个回答将帮助你。

相关问题