Creating empty relational models

Hi,

I can not figure out how to set up model to create some empty relations when its firstly created.

Say I have a product and I want it to have several names in different languages.

I have a relation as follows:




   'translation' => array(self::HAS_MANY, 'translation', 'id'),

Now everything works great for existing products with existing translations. Say I have 3 languages: en, es, it.

So when I edit existing model I get a 3 element array for my $product->translation relation

However when I create new Product my $product->translation is an empty array.

Trying to do something like


$product->translation[] = new Translation; 

fails miserably. How do I do this?

I need it so every new product will have a nice 3 validateable form fields for every language.

You could check this Extenstion to handle HAS_MANY relations: http://www.yiiframework.com/extension/activerecord-relation-behavior/

With this extension you’ll have simply to do something like:




$product->translation = array(new Translation, new Translation, new Translation);

$product->save();



To create the translations and save them with the product.

Hi, thanks.

Actually I did not need an extension - all I was missing was a proper syntax of assignement:


$product->translation = array(new Translation, new Translation, new Translation);

Actually you can also use it in a slightly different way, say if you want to have those models pre filed with some attributes and even add new models to existing ones:




$new_obj = new Translation; //create an empty object

$new_object->language = 'English'; //set an attribute

$this->translation = array_merge($this->translation, array($new_obj)); //merge existing relations with a new one



Thanks again!

I’m glad you solved your problem

The extension was not meant to assign the related object to the parent one, the purpose is more to save the related models with the parent model so instead of doing:


 

$product->translation = array(new Translation, new Translation, new Translation);

// save product

 $product>save();


// save related models

 foreach($product->translation as $tr ) {

        $tr->product_id = $product->id; // set the foreign key

        $tr->save();

    }



you’ll have only to do




$product->translation = array(new Translation, new Translation, new Translation);

// Saving the product and automatically adding the 3 translations in the db with the product id

$product->save();