php 如何仅更新 Yii 中活动记录的特定字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10275542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update only specific fields of an active record in Yii?
提问by lvil
I have a model (ActiveRecord) that has 5 properties(DB columns).
I fetch a specific record and populate a form that has 3 fields(two other fields shouldn't be updated).
Then I change a specific field and press save.
我有一个模型 (ActiveRecord),它有5 个属性(DB 列)。
我获取特定记录并填充一个包含3 个字段的表单(不应更新另外两个字段)。
然后我更改特定字段并按保存。
How to update the record, not touching the fields that are not in form?
如何更新记录,而不触及不在表单中的字段?
采纳答案by Stelian Matei
You could create a method in your controller something like this:
您可以在控制器中创建一个方法,如下所示:
public function actionUpdate($id) {
$model = $this->loadModel($id, 'User');
if (isset($_POST['User'])) {
$model->setAttributes($_POST['User']);
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->id_user));
}
}
$this->render('update', array(
'model' => $model,
));
}
To summarize, the action performs the following:
总而言之,该操作执行以下操作:
- loads the model from the database (with all the values set from the database)
- assigns the values in the form (this will OVERWRITE only the attributes which were sent in the form)
- the model is saved in the database
- 从数据库加载模型(使用从数据库设置的所有值)
- 分配表单中的值(这将仅覆盖表单中发送的属性)
- 模型保存在数据库中
So, you don't need to have all the model attributes in the form. The ones which are defined in the form, will be changed in the model. All other fields will not be changed because the model is loaded from the database before setting the form changes.
因此,您不需要在表单中包含所有模型属性。在表单中定义的那些将在模型中改变。所有其他字段都不会更改,因为模型是在设置表单更改之前从数据库加载的。

