yii2中的model-> attributes始终具有NULL值

b24*_*b24 13 php yii yii-extensions yii2

我有一个临时模型作为viewModel.在我的CRUD操作(例如actionCreate)中,我想获取此viewModel数据并将其分配给ActiveRecord模型.我使用下面的代码但我的模型对象atrribute总是显示属性的NULL值:

$model = new _Users();
if ($model->load(Yii::$app->request->post())) {
    Yii::info($model->attributes,'test'); // NULL
    $attributesValue =[
            'title' => $_POST['_Users']['title'],
            'type' => $_POST['_Users']['type'],
        ];
    $model->attributes = $attributesValue;
    Yii::info($model->attributes,'test'); // NULL

    $dbModel = new Users();
    $dbModel->title = $model->title;
    $dbModel->type = $model->type . ' CYC'; // CYC is static type code
    Yii::info($dbModel->attributes,'test'); // NULL

    if ($dbModel->save()) {
            return $this->redirect(['view', 'id' => $dbModel->id]); // Page redirect to blank page
        }
}
else {
        return $this->render('create', [
            'model' => $model,
        ]);
}
Run Code Online (Sandbox Code Playgroud)

我认为$ model-> load(Yii :: $ app-> request-> post())不工作,对象属性为NULL.是Yii2错误还是我的代码不正确?

Jas*_*n G 20

如果您的属性没有规则,$model->load()则会忽略那些不在模型规则中的规则.

将属性添加到规则函数

public function rules()
{
    return [
        ...
        [['attribute_name'], 'type'],
        ...
    ];
}
Run Code Online (Sandbox Code Playgroud)