Created
September 5, 2012 12:17
-
-
Save pronskiy/3635784 to your computer and use it in GitHub Desktop.
Yii DynamicRelationBehavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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