问题描述
我有两个表menus
和lang_menus
.我的 Menus
模型如下:
I have two tables menus
and lang_menus
. My Menus
model is as follows :
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);
行中.
This is throwing the error Unknown column 'menulanguages.languageId'
.The error is in the line $menus = Menus::model()->with('menulanguages')->findAll($criteria);
.
令人惊讶的是,我正确地获取了变量 $count
的值.
Surprisingly I am getting the value of the variable $count
correctly.
在查看日志时,我可以看到为 findAll 查询运行的 SQL 查询是:
On looking at the log I can see that the SQL query that is running for the findAll query is :
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
这意味着连接尚未发生.而正确的连接查询正在为计数值运行.难道我做错了什么 ?请帮忙.
which means the join has not taken place. Whereas proper join query is running for the count value. Am I doing something wrong ?Please help.
推荐答案
只需使用 together()
of CActiveRecord 或 together
属性:
Just use together()
of CActiveRecord or 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;
这篇关于使用 findAll 时 Yii AR join 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!