Dynamically add relations to model

Hi everyone!

I am creating a model behavoir that should, when attached to model, add two relations to that model.

Does anybody know how to do that ?

I was looking all around but can’t seem to find the answer.

Thanks ;)

Override attach() method in your behavior as follows:




public function attach($owner)

{

  $owner->metaData->addRelation(/* ...see below... */);

  //...

  parent::attach($owner);

}



CActiveRecordMetaData::addRelation()

You are my savior :D

Thank you so much! Worked great ;)

Hello,

Could you give me a exemple, because it doesn’t work for me.

I put this code on my model :




 public function attach($owner)

    {

      $myLangues = BaLangue::model()->findAll();

      foreach ($myLangues as $myLangue) {  

        $owner->metaData->addRelation('nom_'.$myLangue->langue_id,array(self::HAS_ONE, 'adProfilLangue', 'fk_profil','condition'=> 'fk_langue='.$myLangue->langue_id));

      }

      parent::attach($owner);

    }



And in my view:




<?php $myLangues = BaLangue::model()->findAll();

    foreach ($myLangues as $myLangue) {

          $prLangue =  'nom_'.$myLangue->langue_id;

        // $model->setAttribute('nom_edit_'.$myLangue->langue_id);?>

        <div class="row">

            <?php echo $form->labelEx($model,'* '.yii::t('view','nom').' ['.$myLangue->langue_nom.']'); ?>

            <?php echo $form->textField($model->$prLangue,'nom'); // _edit_'.$myLangue->langue_id?>

            <?php echo $form->error($model,'nom_edit_'.$myLangue->langue_id); ?>

        </div>

        

 <?php  } ?>



and the error :

thank you

Nath

Bear in mind that the code shown belongs in a behavior, not in the AR model itself.

thank you, but it still doesn’t work, I am begginer with yii, so everyting is hard for me ;D .

I extends CBehaviour :




class language extends CBehavior

{

    public function attach($owner)

    {

           

      $myLangues = BaLangue::model()->findAll();

      foreach ($myLangues as $myLangue) {  

        $owner->metaData->addRelation('nom_'.$myLangue->langue_id,array(self::HAS_ONE, 'adProfilLangue', 'fk_profil','condition'=> 'fk_langue='.$myLangue->langue_id));

      }

      parent::attach($owner);

    }

}



and I attached behavior to my model in the function relation:




 $this->attachbehavior('blah', new language);

        $this->attach($owner);



To attach a behavior, override the behaviors method in the AR class:




	public function behaviors()

	{

		return array(

			'LanguageBehavior' => 'application.models.behaviors.LanguageBehavior',

		);

	}



Obviously, you need to make sure that the path to the behavior class is correct and that the class name matches.