1

我正在努力在 Yii 中创建正确的查询,但我相信我正在取得进展。

我需要检查相关表,并且只想返回相关表中没有记录的记录。这在这里得到了回答-Yii确定相关模型的存在

使这个复杂化并且我不确定如何克服它的是,多个用户可以在这个相关表中拥有记录。因此,完整的要求是返回不存在相关记录的记录,而只计算登录用户的记录。

两个相关的对象如下——SurveyQuestion AnsweredQuestion

调查问题 HAS_MANY 已回答问题

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))
4

1 回答 1

1

在我发布关于以可视方式运行您的查询的评论后,虽然有一段时间。

我认为您需要将条件放在关系user_idon子句中,而不是condition子句中。因为它只返回子级具有NULLid 和user_id2 的父行。这显然不会发生。但是你需要它在JOIN标准中。所以它应该是:

'answered_questions' => array(self::HAS_MANY, 'AnsweredQuestion', 'question_id',
    'on'=>'answered_questions.user_id = '.Yii::app()->user->id,
    'joinType'=>'LEFT JOIN',
),
于 2012-11-04T10:32:34.003 回答