php - Yii2 set new active record relation on init -
i have one-to-one relationship, there fields thing in table thingextra.
i'm trying initialise new thingextra work when creating new thing, , save them both when thing 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 try create thing:
$thing = new thing; i following exception:
exception: setting read-only property: thing::extra is there anyway round this? or design utterly flawed?
this approach worked pretty in yii1.1
you cannot assign relation this, try instead :
public function init(){ if($this->isnewrecord){ $this->populaterelation('extra', new thingextra()); } } read more activerecord::populaterelation()
Comments
Post a Comment