获取 2 种不同模型的数据 - Yii2



我有一个表格,里面看起来像这样:

<?= $form->field($model, 'comment')->textarea(['rows' => 6]) ?>
<?= $form->field($presentation, 'attendance')->textInput(['maxlength' => true]) ?>
<?= $form->field($presentation, 'couples')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'hire_price')->textInput(['maxlength' => true]) ?>

然后我用控制器收集接收到的数据,如下所示:

$model = new PresentationPlaceHistory();
$presentation = new Presentations();
if ($model->load(Yii::$app->request->post()) && $model->save() && $presentation->load(Yii::$app->request->post())) {
    $pres = $presentation->findOne($model->presentation_id);
    $pres->attendance = $presentation->load(Yii::$app->request->post('attendance'));
    $pres->couples = $presentation->load(Yii::$app->request->post('couples'));
    $pres->save();
    return $this->redirect(['view', 'id' => $model->id]);
}
else {
    return $this->render('create', [
        'model' => $model,
        'presentation' => $presentation,
    ]);
}

但实际上,它保存了所有设置为 0 的"出勤"和"夫妇"(在此形式之前它们是空的)。

不管我输入什么数字,我都会得到零。它甚至不必是数字,因为验证根本不起作用。

更改以下两行:

$pres->attendance = $presentation->load(Yii::$app->request->post('attendance'));
$pres->couples = $presentation->load(Yii::$app->request->post('couples'));
// to this
$pres->attendance = $presentation->attendance;
$pres->couples = $presentation->couples;

您已经在此处加载了$presentation$presentation->load(Yii::$app->request->post())并且应该可以直接访问。

有点

混乱的代码你到了这里。首先,我建议你不要使用load()方法,但这是我个人的偏好。阅读有关负载的更多信息。此方法返回 boolean ,这就是您在模型属性中获取0的原因。通常,您的代码应该更像:

$model->load(Yii::$app->request->post());
if ($model->save()) {
    $pres = $presentation->findOne($model->presentation_id);
    $pres->attendance = $presentation->attendance;
    //etc ...
    $pres->save()
}

我不知道你的代码有什么意义,但这看起来有点毫无意义。尝试使用属性,它是所有模型属性的数组。或者指定手动需要的模型属性。

控制器

代码有问题,请更改以下两行

if ($model->load(Yii::$app->request->post()) && $model->save() && $presentation->load(Yii::$app->request->post())) {
        $post_data=  Yii::$app->request->post();
        $pres = $presentation->findOne($model->presentation_id);
        /* change these two lines */
        $pres->attendance = $post_data['Presentations']['attendance'];
        $pres->couples =$post_data['Presentations']['couples'];
        /* change these two lines */
        $pres->save();
        return $this->redirect(['view', 'id' => $model->id]);
  } 
  else 
  {
        return $this->render('create', [
            'model' => $model,
            'presentation' => $presentation,
        ]);
  }

最新更新