模型-> Yii2 中的属性总是有 NULL 值

2022-01-04 00:00:00 php yii2 yii yii-extensions

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

I have one temporary model as viewModel. In my CRUD actions (for example actionCreate) I want to get this viewModel data and assign that to a ActiveRecord model. I used below code but my model object atrribute always show NULL value for attributes:

$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,
        ]);
}

我认为 $model->load(Yii::$app->request->post()) 不起作用并且对象属性为 NULL.是 Yii2 的 bug 还是我的代码不正确??

I think $model->load(Yii::$app->request->post()) not working and object attribute being NULL. Is it Yii2 bug or my code is incorrect??

推荐答案

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

If there is no rule for your attribute the $model->load() will ignore those not in the rules of the model.

将您的属性添加到规则功能

Add your attributes to the rules function

public function rules()
{
    return [
        ...
        [['attribute_name'], 'type'],
        ...
    ];
}

相关文章