model-gt;attributes in Yii2 always has NULL value(模型- 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 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:模型-> Yii2 中的属性总是有 NULL 值


- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01