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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)