Skip to content

Instantly share code, notes, and snippets.

@pronskiy
Created September 5, 2012 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pronskiy/3635784 to your computer and use it in GitHub Desktop.
Save pronskiy/3635784 to your computer and use it in GitHub Desktop.
Yii DynamicRelationBehavior
class DynamicRelationBehavior extends CActiveRecordBehavior
{
/**
* @var string name of the relation which will be added to the owner dynamically
*/
public $relationName = 'posts';
public function afterFind($event)
{
$this->addRelation();
}
public function afterConstruct($event)
{
$this->addRelation();
}
protected function addRelation()
{
// quit if relation is already attached
if ($this->owner->getMetaData()->hasRelation($this->relationName)) return;
$this->owner->getMetaData()->addRelation($this->relationName, array(
CActiveRecord::HAS_MANY,
'Post',
'author_id',
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment