Yii2 ActiveRecord 有一个方法可以使用 load()
自动将表单数据加载到模型中。这非常好,因为它可以安全地使用数据加载模型,但是我找不到一种等效的方法来卸载所有属性的模型。
即是否有一种方法可以在 Yii2 中取消设置模型的所有属性,例如 unSetAttributes()
Yii 1.x 中的方法?
目前这样做的唯一方法似乎是
$model->setAttributes(['attribute1'=>NULL,'attribute2' => NULL ... ]);
或者
foreach ($model->attributes as $attribute) {
$model->$attribute = NULL;
}
编辑 : 澄清回应Samuel Liew's answer ,虽然此时我只想取消我可以通过重新初始化模型来完成的所有属性,但我还想控制哪些属性正在重置,即
unSetAttributes
假如
最佳答案
您可以简单地创建模型的新实例。
$model = new MyModel;
或者如您所见,unsetAttributes in Yii 1就像这样,你可以简单地在你的基本模型中实现它:
public function unsetAttributes($names=null)
{
if($names===null)
$names=$this->attributeNames();
foreach($names as $name)
$this->$name=null;
}
关于activerecord - Yii2:ActiveRecord 如何卸载/取消设置所有(某些)属性的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131885/