简体   繁体   中英

In yii how can I ensure my HAS_ONE child relation is always created along with the parent model

I have 2 Yii AR models. A ParentRecord and a ChildRecord models.

The parent HAS_ONE child.

When creating a new parent, how can I ensure a child is always created as well. A parent always needs a child.

would it be as simple as doing this within the parent AR class?

public function onAfterConstruct()
{
    if ($this->isNewRecord){
        $this->master = new ChildRecord;
    }
}

I do not want to create both within the controller and save them both there, I only want to create and save the parent only, and have the child always created and saved.

I have the relations() array working fine.

just create the child record in after successful save of new parent

public function afterSave()
{
    if($this->isNewRecord)
    {
        $child = new ChildRecord;
        $child->parent_id = $this->id;
        $child->save();
    }

   return parent::afterSave();
}

UPDATE you can go with the relation

public function afterSave()
{
    if($this->isNewRecord)
    {
        $this->childRelation = new ChildRecord;
        $this->childRelation->parent_id = $this->id;
        $this->childRelation->save();
    }

   return parent::afterSave();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM