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 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch