多模型合一模型Yii2


Multiple model in one model Yii2

我想在一个表单中创建多个模型。

这是我的控制器:

public function actionWorkRoom() {
    $model = [new Moshtari()];
    $model[0] = new Moshtari();
    $model[1] = new Moshtari();
    if (Model::loadMultiple($model, Yii::$app->request->post()) && Model::validateMultiple($model)) {
        foreach ($model as $m) {
            $m->save(false);
        }            
   }
    return $this->render('_form_work_room', ['model' => $model]);
}

型号:

    class Moshtari extends 'yii'db'ActiveRecord {
        public function rules() {
                return [
                    [['CodeKargah'], 'number'],
                ]
        }
        public function attributeLabels() {
             return [
                'CodeKargah' => Yii::t('app', 'Code Kargah'),
             ];
    }
    }

这是我的看法:

foreach ($model as $index => $m) {
     echo $form->field($m, "[$index]CodeKargah");
}

但这引发了一个错误:

在非对象上调用成员函数getActiveValidators()

我解决了,这是新代码:

控制器:

public function actionWorkRoom($member = 1) {
    $model[] = new Moshtari(['scenario' => 'work_room_kargah']);
    for ($i = 0; $i < $member; $i++) {
        $model[] = new Moshtari(['scenario' => 'work_room']);
    }
    if (Model::loadMultiple($model, Yii::$app->request->post()) && Model::validateMultiple($model)) {
        foreach ($model as $m) {
            $m->time = Yii::$app->jdate->date('Y/m/d') . ' ' . date('H:i:s');
            $m->CodeKargah = $model[0]->CodeKargah;
            $m->save(false);
        }
        return $this->redirect('index');
    }
    return $this->render('_form_work_room', ['models' => $model]);
}

查看

foreach ($models as $index => $model) {
    //print_r($model->getErrors());
    if ($index >= 1) {
                    <?=
                    $form->field($model, "[$index]name", [
                        'template' => '<div class="row nomargin"><div class="col-md-4 form_label">{label}</div><div class="col-md-7">{input}{error}</div></div>']
                    )->textInput(['maxlength' => true])
                    ?>
    }
}