AR Relations in Behavior

so I’m trying to create a TreeBehaviour – but according to http://www.yiiframework.com/forum/index.php?/topic/7618-potential-new-active-record-behavior-features/ it seems that we can’t put the AR relations in the behavior itself. any hints so that tree behavior that I create can be non-redundant when it will be used in another model?

my current code,

Category.php:




public function behaviors(){

    return array(

        'TreeBehavior' => array(

            'class' => 'application.components.behaviors.TreeBehavior',

            'modelClassName' => 'Category',

            'parent_field' => 'parent_id'

        )

    );

}



TreeBehavior.php:




class TreeBehavior extends CActiveRecordBehavior {

	public $modelClassName;

	public $parent_field;

	

	public function relations() {

		return array(

			'parent' => array(self::BELONGS_TO, $this->modelClassName, $this->parent_field),

			'children' => array(self::HAS_MANY, $this->modelClassName, $this->parent_field),

			'num_children' => array(self::STAT, $this->modelClassName, $this->parent_field),

		);

	}

	public function setParent($parentNode) {

		$this->Owner->parent = $parentNode;

	}

	public function beforeSave() {

		if ($this->Owner->parent===null) {

			$this->Owner->level = 1;

		} else {

			$this->Owner->level = $this->Owner->parent->level + 1;

		}

	}



thanks in advance

From a quick look at the source i would say, something like this should work:


$this->Owner->getMetaData()->addRelation('children'=>array(...));

Not sure if it helps, though.

thank you mike this was the right hint

I’m very new to behaviors in yii and not sure if there exists some init anywhere but my code looks now like this:




public function attach($owner)

{  

    parent::attach($owner);

    $this->getOwner()->getMetaData()->addRelation('getValues', array(CActiveRecord::BELONGS_TO, 'MyValues', 'valuesId));

}

This thread may be old but pops up first when searching for this subject :)

Thanks balrok, this was very helpful.