Activerecord不与嵌套关系连接


Yii Activerecord doesn't join with nested relation

我在Yii中定义了以下条件,并尝试使用它来获取客户数组。

$criteria = new CDbCriteria(array(
        "condition"=>"hidden = 0".(Yii::app()->user->GetState('is_admin') ? "" : " AND franchisesMunicipalities.franchise_id=".Yii::app()->user->getState('fid')),
        "with" => array('municipality','municipality.franchisesMunicipalities')
));
$customers = Customers::model()->findAll($criteria);

这(我认为)应该导致Yii将表Customers与表Municipalities连接起来,然后在同一个查询中将表Municipalities与表franches_municipalities连接起来。然而,它不起作用,因为它不加入特许经营权。

结果查询如下

SELECT `t`.`id`                   AS `t0_c0`, 
   `t`.`municipality_id`      AS `t0_c1`, 
   `t`.`personal_code_number` AS `t0_c2`, 
   `t`.`name`                 AS `t0_c3`, 
   `t`.`adress`               AS `t0_c4`, 
   `t`.`zip`                  AS `t0_c5`, 
   `t`.`phone`                AS `t0_c6`, 
   `t`.`mobile`               AS `t0_c7`, 
   `t`.`email`                AS `t0_c8`, 
   `t`.`hidden`               AS `t0_c9`, 
   `municipality`.`id`        AS `t1_c0`, 
   `municipality`.`county_id` AS `t1_c1`, 
   `municipality`.`name`      AS `t1_c2` 
FROM   `customers` `t` 
   LEFT OUTER JOIN `municipalities` `municipality` 
                ON ( `t`.`municipality_id` = `municipality`.`id` ) 
WHERE  ( hidden = 0 
     AND municipality.franchisesmunicipalities.franchise_id = 7 ) 
LIMIT  30 

可以看到,它只连接一个关系。模型中的关系应该正确定义,因为我可以在其他上下文中使用它们。

为什么这个不行?

根据http://www.yiiframework.com/doc/api/1.1/CActiveRecord#with-detail,我相信你应该这样做:

$criteria = new CDbCriteria(array(
        "condition"=>"hidden = 0".(Yii::app()->user->GetState('is_admin') ? "" : " AND franchisesMunicipalities.franchise_id=".Yii::app()->user->getState('fid'))
));
$customers = Customers::model()->with('municipality','municipality.franchisesMunicipalities')->findAll($criteria);