我需要停止更新某些值,即使这些值被设置为POST数组。为了做到这一点,我在yii规则中使用了unsafe。
array('id', 'unsafe', 'on'=>'update'),
尽管如此,我还是无法跳过更新id。
yii怎么能做到这一点?
下面是我的规则函数。。
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, body, created_date', 'required'),
array('name', 'length', 'max'=>128),
array('body', 'length', 'max'=>512),
array('id', 'unsafe', 'on'=>'update'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, body, created_date', 'safe', 'on'=>'search'),
);
}
更新1
$model->attributes=$_POST["用户"];
保存时,我需要跳过某些属性。
$model->save();
在控制器中创建新模型实例时,需要声明场景例如如果你的申报单是类似的
$myModelInstance = new MyModel();
您需要将其更改为
$myModelInstance = new MyModel('update');
但是,如果您使用活动记录的查找方法之一进行保存,则会自动设置为"更新",如下所示:http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-详细
如果您使用其他一些逻辑来声明模型,您可以简单地使用setScenario函数
$myModel->setScenario("update");
正如Manquer所提到的,您的场景可能没有设置为更新。正确的更新顺序包括加载现有的对象实例,分配变量,然后保存它们。我个人永远不会只是实例化一个对象,然后给它一个不同的场景,我认为这是在问问题。
// Load the existing object first
$user = User::model()->findByPk(..);
// Assign everything that has either a validation rule or is added as "safe"
$user->attributes = $_POST['User'];
// Save the updated version
$user->save();
Yii知道不要更新"id"(如果它被正确定义为数据库中的主键)。没有必要将其标记为不安全。所以:确保实例是从数据库加载的($user->isNewRecord应该为FALSE),并且表有PK。然后更新你想要的属性。
您也只能通过首先"清理"$_POST来更新特定属性,或者当您调用save时,只需将其调用为$user->save(true,array('name','body'))即可仅更新名称和正文。
对于Yii2:
如果因为必须手动应用场景而不想使用场景,则可以在rules()
:中使用when
['moduleID', 'required', 'when' => function($model, $attribute) {
return $model->isNewRecord;
}],
或者,如果您有许多属性规则,并且不想将when
添加到所有规则中,您可以简单地禁止beforeSave()
方法中的更改:
public function beforeSave($isInsert) {
$attribute = 'moduleID';
if (!$isInsert && $this->isAttributeChanged($attribute)) {
$this->addError($attribute, 'You cannot change this.');
}
return parent::beforeSave($isInsert);
}