模型-> Yii2 中的属性总是有 NULL 值 [英] model->attributes in Yii2 always has NULL value

查看:62
本文介绍了模型-> Yii2 中的属性总是有 NULL 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个临时模型作为 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'],
        ...
    ];
}

这篇关于模型-> Yii2 中的属性总是有 NULL 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆