Reputation: 5333
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.
Upvotes: 0
Views: 67
Reputation: 7265
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();
}
Upvotes: 2