Arth
Arth

Reputation: 13110

Yii2 set new active record relation on init

I have a one-to-one relationship, where there are extra fields for Thing in a table ThingExtra.

I'm trying to initialise a new ThingExtra to work with when creating a new Thing, and then save them both when Thing is saved:

class Thing extends ActiveRecord
{
    public function init(){
        if($this->isNewRecord){
            $this->extra = new ThingExtra();
        }
    }

    public function getExtra(){
        return $this->hasOne(ThingExtra::className(),['thing_id' => 'id']);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $this->extra->thing_id = $this->id;
        $this->extra->save();
    }
}

Now when I try to create a Thing:

$thing = new Thing;

I get the following exception:

Exception: Setting read-only property: Thing::extra

Is there anyway round this? Or is my design utterly flawed?

This approach worked pretty well for us in Yii1.1

Upvotes: 2

Views: 1700

Answers (1)

soju
soju

Reputation: 25312

You cannot assign a relation like this, you could try this instead :

public function init(){
    if($this->isNewRecord){
        $this->populateRelation('extra', new ThingExtra());
    }
}

Read more about ActiveRecord::populateRelation()

Upvotes: 8

Related Questions