我正在努力在Yii中创建正确的查询,我相信我正在取得进展。
我需要检查一个相关的表,只想返回相关表中没有记录的记录。这在这里得到了解答 - Yii determining existence of related models
使这种情况复杂化的原因是我不确定如何克服它,多个用户可以在此相关表中拥有记录。因此,完整的要求是返回不存在相关记录的记录,但仅记录登录用户的记录。
两个相关对象如下─ SurveyQuestion AnsweredQuestion
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))
答案 0 :(得分:1)
在发布关于直观地运行查询的评论后,我发现了。
我认为您需要将user_id
的条件放在关系的on
子句中,而不是condition
子句中。因为它只返回子行中NULL
id和user_id
为2的父行。这显然不会发生。但是你需要它符合JOIN
标准。所以它应该是:
'answered_questions' => array(self::HAS_MANY, 'AnsweredQuestion', 'question_id',
'on'=>'answered_questions.user_id = '.Yii::app()->user->id,
'joinType'=>'LEFT JOIN',
),