我有两个表menuslang_menus。我的Menus模型如下:

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
                'menulanguages'=>array(self::HAS_MANY, 'MenuLangs', 'menuId'),
    );
}
...
public function getMenus(){
        $criteria = new CDbCriteria();
        $criteria->condition = "t.clientId = ".Yii::app()->user->clientId." AND menulanguages.languageId = ".Yii::app()->user->userlanguage;


        $count = Menus::model()->with('menulanguages')->count($criteria);

        $pages=new CPagination($count);
        //Results per page
        $pages->pageSize=10;
        $pages->applyLimit($criteria);

        $menus = Menus::model()->with('menulanguages')->findAll($criteria);
        return array('menus' => $menus, 'paging' => $pages);
    }

这将引发错误Unknown column 'menulanguages.languageId'
错误在$menus = Menus::model()->with('menulanguages')->findAll($criteria);行中。

令人惊讶的是,我正确地获得了$count变量的值。

在查看日志时,我可以看到为findAll查询运行的SQL查询是:
SELECT `t`.`id` AS `t0_c0`, `t`.`clientId` AS `t0_c1`, `t`.`restaurantId` AS `t0_c2` FROM `posif_menus` `t` WHERE (t.clientId = 1 AND menulanguages.languageId = 2) LIMIT 10

这表示尚未进行加入。而正确的联接查询正在运行以获取计数值。难道我做错了什么 ?
请帮忙。

最佳答案

只需使用 together() of CActiveRecord together property of CDbCriteria即可:

$menus = Menus::model()->with('menulanguages')->together()->findAll($criteria);

要么:
$criteria = new CDbCriteria();
$criteria->condition = "t.clientId = ".Yii::app()->user->clientId." AND menulanguages.languageId = ".Yii::app()->user->userlanguage;
$criteria->together=true;

关于php - Yii AR Join在使用findAll时不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10697047/

10-10 02:51