【发布时间】:2012-11-03 18:16:41
【问题描述】:
我正在努力在 Yii 中创建正确的查询,但我相信我正在取得进展。
我需要检查相关表,并且只想返回相关表中没有记录的记录。这是在这里回答的-Yii determining existence of related models
使这个问题复杂化并且我不确定如何克服它的是,多个用户可以在这个相关表中拥有记录。因此,完整的要求是返回不存在相关记录的记录,而只计算登录用户的记录。
两个相关的对象如下—— 调查问题 已回答问题
SurveyQuestion HAS_MANY AnsweredQuestion
AnsweredQuestion 表具有以下列-
id -survey_question_id -user_id
survey_question_id 是 SurveyQuestion 表的外键。
到目前为止,我的方法是尝试将记录限制为与具有关系定义的登录用户相关的记录-
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(
'survey_answer'=>array(self::HAS_MANY,'SurveyAnswer','survey_question_id'),
'answered_questions' => array(self::HAS_MANY, 'AnsweredQuestion', 'question_id',
'condition'=>'answered_questions.user_id = '.Yii::app()->user->id,
'joinType'=>'LEFT JOIN',
),
);
}
为了将查询限制在父表中的记录,而子表中没有相关记录,我在 findAll 函数中使用了一个条件,如下所示-
$questions = SurveyQuestion::model()->with(array(
'survey_answer',
'answered_questions'=>array(
'select'=>false,
'joinType'=>'LEFT JOIN',
'condition'=>'`answered_questions` . `id` is NULL'
),))->findAll();
即使清除子表,这两条代码也不返回任何结果。
谁能发现我哪里出错了,在方法上还是在执行上?
非常感谢,
尼克
更新
根据要求,这是运行的 sql 语句。相关的是第二个 Join,第一个 Join 收集多项选择答案。
SELECT `t`.`id` AS `t0_c0`, `t`.`area_id` AS `t0_c1`,
`t`.`question_text` AS `t0_c2`, `t`.`date_question` AS `t0_c3`,
`survey_answer`.`id` AS `t1_c0`, `survey_answer`.`survey_question_id` AS
`t1_c1`, `survey_answer`.`answer_text` AS `t1_c2`, `survey_answer`.`tag_id`
AS `t1_c3` FROM `tbl_survey_questions` `t` LEFT OUTER JOIN
`tbl_survey_answers` `survey_answer` ON
(`survey_answer`.`survey_question_id`=`t`.`id`) LEFT JOIN
`tbl_answered_questions` `answered_questions` ON
(`answered_questions`.`question_id`=`t`.`id`) WHERE
((answered_questions.user_id = 2) AND (`answered_questions` . `id` is
NULL))
【问题讨论】:
-
你能通过查看日志看到它实际构建的是什么SQL吗?打开您的博客并在您的数据库连接上启用分析。 yiiframework.com/wiki/235/…
-
谢谢你,我以前从来没有打开过分析功能。我已经添加了它运行的 sql。
-
您是否安装了 PHPMyAdmin 或任何其他 SQL 接口,您可以通过视觉方式实际对您的数据库运行它?我看不出该查询有任何明显错误。
标签: web-applications yii findall