简体   繁体   English

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

[英]how to insert data to 2 tables from single form and controller in yii2

this is my create page 这是我的创建页面

questions/create.php 问题/ 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 askid是另一个表中的字段

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 我已经为Askquestions表生成了模型和Crud,并且还在控制器和视图页面中包含了类,但是数据未插入表中,这是可能的方法

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. 但是,针对此问题的最佳解决方案是创建和创建与LoginForm相同的表单模型,该表单模型将具有所有属性的单一表单,并且可以在单一模型中应用验证。 Once everything is posted and validated then you can save the values to the respective models 发布所有内容并进行验证后,您可以将值保存到相应的模型中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM