简体   繁体   English

Yii,多个MANY_MANY关系

[英]Yii, Multiple MANY_MANY relations

Ok so i have two models: 好的,所以我有两个模型:

1: pv_array (photovoltaic array) 2: module (photovoltaic module) 1:pv_array(光伏阵列)2:模块(光伏模块)

there is a MANY_MANY relation between both of them: 两者之间存在MANY_MANY关系:

        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. 问题是,当我将模块添加到阵列中时,我需要能够将同一模块的多个实例添加到阵列中……我可以做到这一点,当我检查数据库表module_to_array时,存在多个条目。

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 例如,如果我将3 x ModuleXYZ和2x ModuleABC添加到Array1中,我只会得到以下内容

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

where i would want it to echo 5 我想让它回显5

any idea? 任何想法?

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 好的,经过大约4个小时的编码,我找到了解决此问题的最佳方法……只是用一种魔术方法手动进行关系

  1. first comment out the relation 首先注释掉关系

  2. create a magic property the same as the relation propery eg 创建与关系属性相同的魔法属性,例如

      var $_modules = array(); 
  3. use the magic get method and dbcriteria to build the query manually 使用魔术的get方法和dbcriteria手动构建查询

     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); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM