phpmysqlactiverecordyiiyii-cmodel

Yii, Multiple MANY_MANY relations


Ok so i have two models:

1: pv_array (photovoltaic array) 2: module (photovoltaic module)

there is a MANY_MANY relation between both of them:

        return array(           
                'modules' => array(self::MANY_MANY, 'module', 'module_to_array(array_id, module_id)'),
        );

        return array(
                'arrays' => array(self::MANY_MANY, 'pv_array', 'module_to_array(module_id, array_id)'),
        );

The problem is when i add modules to an array i need the ability to add multiple instances of the same module to an array... i can do this no problem, when i check the Database table module_to_array there are multiple entries present.

Although when i now go to access the modules in the array as follows:

$pv_array = pv_array::model()->findByPk( 2 );
echo count( $pv_array->modules);

it only counts single instances of modules and not the multiple instances of modules as are present...??

for example if i added 3 x ModuleXYZ and 2x ModuleABC to Array1 i would only get the following

echo count( $Array1->modules ); // would echo 2

where i would want it to echo 5

any idea?


Solution

  • ok i discovered the best solution to this problem after about 4 hours of wading through code... just to do the relation manually with a magic method

    1. first comment out the relation

    2. create a magic property the same as the relation propery e.g

          var $_modules = array();
      
    3. use the magic get method and dbcriteria to build the query manually

      public function getModules() 
      {
           $criteria = new CDbCriteria;
           $criteria->join = 'LEFT JOIN component_to_array ON component_to_array.array_id = '.$this->id.' AND t.id = component_to_array.component_id';
           $criteria->condition = 'component_to_array.array_id = '.$this->id.'';
      
           return component::model()->findAll($criteria);
      }