Save parent model and child models with HAS_MANY relation to database with Active Record

I have a Parent class which has many children. Currently I’m using this to save the parent and several children:




$model = new Parent();

$model->attributes = $someAttributes;

$model->save();


$child = new Child();

$child->atributes = $otherAttributes;

$child->parentId = $model->id; /* foreign key */

$child->save();



This code works, but becomes cluttered and complicated when multiple children need to be validated. The parent’s id is required for validation, but the parent should not be saved to the database when one or several children don’t validate.

Something like this would be great:




$model = new Parent();

$model->attributes = $someAttributes;

$model->children[0]->attributes = $otherAttributes;

$model->save();



But I can’t find any documentation about this. Is this supported? When it is not, why? When it is, how can I use it?

Other solutions for my parent/children validation problem?

Unfortunately Yii does not provide anything as a solution as i know. But in the extensions here extension to do that(i do not know the name, you have to have a look), in order to validation u have to beforeValidate() method of parent object u just override this method inside parent object class then before validating parent obj the code inside the method will be invoked.

thanks.

You can try wform extension. Hope, it will work for you.

Thanks guys for the suggestions. I was using rules to validate the foreign key and other attributes which are not entered by the user. I removed all the rules which are not used for user input. Now I can just use:




$model = new Parent();

$model->attributes = $someAttributes;


if($model->validate()){

    $child = new Child();

    $child->atributes = $otherAttributes;

    if($child->validate()){

        $model->save();

        $child->parentId = $model->id;

        $child->save();

    }

}



Implementing the same functionality with a rule on parentId makes it a lot more complicated. Using validation rules to maintain database integrity is also bad practice, because an attempt to break the integrity should result in an Exception, not in a validation error.

Dana Luther created a ‘children required’ validator that may help solve this problem.