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

288

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.

999

Answer

Solution:

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();
}

People are also looking for solutions to the problem: php - Unable to submit form in 404 page

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.