我有两张表menus
和lang_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
表示尚未进行加入。而正在为计数值运行正确的连接查询。难道我做错了什么 ? 请帮忙。
答案 0 :(得分:5)
只需使用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;
答案 1 :(得分:2)
试试这个..在cdbcriteria中应用连接表..
public function getMenus(){
$criteria = new CDbCriteria();
$criteria->condition = "t.clientId = ".Yii::app()->user->clientId." AND menulanguages.languageId = ".Yii::app()->user->userlanguage;
$criteria->with = array('menulanguages');
$count = Menus::model()->count($criteria);
$pages=new CPagination($count);
//Results per page
$pages->pageSize=10;
$pages->applyLimit($criteria);
$menus = Menus::model()->findAll($criteria);
return array('menus' => $menus, 'paging' => $pages);
}