Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: ActiveRecord How to unload / unset a model of all(some) attributes?

Yii2 ActiveRecord has a method to automatically load a form data into a model using load() which is very good as it safely loads the model with data, However I am not able find a equivalent method to unload the model of all the attributes.

i.e. Is there a method to unset all attributes of a model in Yii2, like the unSetAttributes() method in Yii 1.x ?

Currently the only way to do this seems to be either

$model->setAttributes(['attribute1'=>NULL,'attribute2' => NULL ... ]);

or

foreach ($model->attributes as $attribute) {
    $model->$attribute = NULL; 
}

Edit: To clarify in response to Samuel Liew's answer, while at this point I only wanted to unset all attributes which I could do by reiniting the model, I would also like to control which attributes are getting reset, which unSetAttributes provided

like image 883
Manquer Avatar asked Aug 05 '14 05:08

Manquer


1 Answers

You could simply create a new instance of the model.

$model = new MyModel;

Or as you can see, unsetAttributes in Yii 1 is like this, you could simply implement it in your base model:

public function unsetAttributes($names=null)
{
    if($names===null)
        $names=$this->attributeNames();
    foreach($names as $name)
        $this->$name=null;
}
like image 132
Samuel Liew Avatar answered Nov 12 '22 12:11

Samuel Liew