0

我试图让这个 mysql 查询与 Yii 模型一起工作,但我不能。

SELECT COUNT( qhc.countries_id) AS counter, q.question, co.name 
FROM questions AS q , countries as co, questions_has_countries AS qhc
WHERE qhc.questions_id = q.id 
AND co.id = qhc.countries_id
GROUP BY question
HAVING counter = 2

到目前为止,我有这个,但不知何故,你似乎没问题,它不起作用:

$criteria = new CDbCriteria(); 
$criteria->select = 'question, COUNT(countries_id) as counter';
$criteria->with = array('countries', 'categories');
$criteria->addInCondition('countries.id' , $_POST['Questions']['countries']);
$criteria->group = 'question';
$criteria->having = ('counter = 1');
$model = Questions::model()->findAll($criteria)

请帮忙,我对 Yii 框架很陌生。

谢谢。

来自日志的 Sql:

SELECT `t`.`question` AS `t0_c1`,
COUNT(countries_id) as counter, `t`.`id` AS `t0_c0`, `countries`.`id` AS
`t1_c0`, `countries`.`name` AS `t1_c1`, `categories`.`id` AS `t2_c0`,
`categories`.`name` AS `t2_c1` FROM `questions` `t`  LEFT OUTER JOIN
`questions_has_countries` `countries_countries` ON
(`t`.`id`=`countries_countries`.`questions_id`) LEFT OUTER JOIN `countries`
`countries` ON (`countries`.`id`=`countries_countries`.`countries_id`) 
LEFT OUTER JOIN `questions_has_categories` `categories_categories` ON
(`t`.`id`=`categories_categories`.`questions_id`) LEFT OUTER JOIN
`categories` `categories` ON
(`categories`.`id`=`categories_categories`.`categories_id`)  WHERE
(countries.id=:ycp0) GROUP BY question HAVING (counter = 2). Bound with
:ycp0='1'
4

3 回答 3

1

你已经完成了大部分工作。现在你需要调用$criteriainto 模型。像这样

$rows = MODEL ::model()->findAll($criteria);

MODEL您要应用标准的表的模型类在哪里。

要了解有关此的更多信息,您可以关注此CActiveRecord 类

于 2013-09-14T19:18:14.463 回答
1

尝试together设置CDbCriteria

...
$criteria->together = true;
$model = Question::model()->findAll($criteria);
于 2013-09-16T00:10:50.937 回答
0

当您使用“作为计数器”时,您的模型必须有一个名为“计数器”的属性,否则它不会将其加载到您的模型中。

如果您没有名为“counter”的属性,请尝试使用您现在没有选择的另一个模型属性:“as someColumn”

并使用 condition 或 addCondition 或 .. 而不是

干杯

于 2013-09-15T13:03:06.713 回答