douguanya6399 2016-07-12 12:45
浏览 60
已采纳

如何在yii2中从单个表单和控制器向2个表插入数据

this is my create page

questions/create.php

<?php $form = ActiveForm::begin(); ?>
<br><br><br>
<?= $form->field($model, 'question')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'topic')->textInput(['maxlength' => true]) ?>
<?= $form->field($model1, 'askid')->textInput(['maxlength' => true]) ?>

 <div class="form-group">
  <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') :   Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
  </div>

<?php ActiveForm::end(); 

askid is the field in another table askquestions

questioncontroller

public function actionCreate()
{
    $model = new Questions();
    $model1 = new Askquestions();

     //$model1 -> load(Yii::$app->request->post());



    if ($model1->load(Yii::$app->request->post())) {
        //$model->user_id=Yii::$app->user->identity->id;
         if($model1->save())
        return $this->redirect(['index']);
     } else {
        return $this->render('create', [
            'model' => $model, 'model1' => $model1,
        ]);
    }
   }

i have generated model and crud for askquestions table and also included class in the controller and view page but the data is not inserting in the table what would be the possible way

  • 写回答

1条回答 默认 最新

  • douzuo0002 2016-07-12 13:01
    关注

    The possible solution would be: (not tested)

    public function actionCreate()
    {
        $model = new Questions();
        $model1 = new Askquestions();
    
        if ($model->load(Yii::$app->request->post()) && $model1->load(Yii::$app->request->post())) {
            //$model->user_id=Yii::$app->user->identity->id;
             if($model->save() && $model1->save())
            return $this->redirect(['index']);
         } else {
            return $this->render('create', [
                'model' => $model, 'model1' => $model1,
            ]);
        }
       }
    

    Try the above code once.

    But the best Solution for this problem will be creating and Form Model same like LoginForm it will have all the attributes in single form and validations can be applied on in single model. Once everything is posted and validated then you can save the values to the respective models

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wpf通过绑定控件自身的值,来实现背景颜色的切换
  • ¥15 CDH6.3 运行hive -e hive -e "show databases;"报错:hive-env.sh:行24: hbase-common.jar: 权限不够
  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线