lazy loading of MANY_MANY Relations


is it possible to lazy load a MANY_MANY Relation with CActiveRecord yet?

For example, let’s assume we have Post and Categories with a Many_many Relation:

$post = Post::model()->findByPk(11);


should print an array of Category Objects that’s been attached to the Post Nr. 11.

i don’t think it is possible yet, and that’s why i wanted to include this magic in my CAdvancedArBehavior, but i ran into some problems.

Overriding the __get() magic function of PHP in an Behavior doesn’t seem to work - the function

simply doesn’t get run when calling it with the behavior attached:

  public function __get($value) {

    return parent::__get($value) . 'test';


so, my simple question: is there a way to lazy load Many_Many Relations with ActiveRecord and if not:

how is it possible to override the default behavior of CActiveRecord without using __get() ?

This is my workaround:

  public function getRelatedManyManyObjects() {

                $sql = sprintf("select * from %s where %s = %s",




                $result = Yii::app()->db->createCommand($sql)->queryAll();

                foreach($result as $foreignObject) {

                        $objects[] = $foreignObject[$this->manyManyTableRight];


                return $objects;


assuming that:

 preg_match_all('/^.*\(/', $value[2], $matches);

                                        $this->manyManyTable = substr($matches[0][0], 0, strlen($matches[0][0]) -1);

                                        preg_match_all('/\(.*,/', $value[2], $matches);

                                        $this->manyManyTableLeft = substr($matches[0][0], 1, strlen($matches[0][0]) - 2);

                                        preg_match_all('/,.*\)/', $value[2], $matches);

                                        $this->manyManyTableRight = substr($matches[0][0], 2, strlen($matches[0][0]) - 3);

this works, but it would be much cooler implemented in the ActiveRecord.

btw: my need to have this feature is the implementation in my Relation Widget, which now support MANY_MANY Relations…

Any related records will be lazy loaded when accessing the relation property the first time. Are you sure your relations are set up correctly? Maybe try to test with a simplified model.