Yii ActiveRecord model save by chain

77 views Asked by At

There is a model:

class Model extends ActiveRecord
{
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    public function toSave(Array $data)
    {
        $this->setAttributes($data);
        $this->save(); // returns true
        return $this;
    }
}

and running

$model = Model::model()->toSave($data);

and when im dumping $model there is all data which setted from $data but not exists PrimaryKey (id).

but, if i run

$model = new Model;
$model->toSave($data);

works as expected.

Where is a problem?

2

There are 2 answers

0
ramamoorthy_villi On

you are doing multiple save, through iterating, and pass new set of $data everytime. $model here is an object of single record. So by doing everytime, new model , you are creating fresh new object, assign data and save. Later you did is the right approach.

0
crafter On

You usage in invalid in the first instance

$model = Model::model()->toSave($data);

In this case, the usage is calling the toSave() method statically.

First, the usage is illegal unless you change your declaration

public static  function toSave(Array $data) { ... }

In addition, when invoked statically, the value for $this is invalid.

Therefore, the valid usage is your second version:

$model = new Model;
$model->toSave($data);

References: http://php.net/manual/en/language.oop5.static.php