Yii で正しいクエリを作成するのに苦労していますが、進歩していると思います。
関連テーブルをチェックする必要があり、関連テーブルにレコードがないレコードのみを返したい。これはここで回答されました-Yiiは関連モデルの存在を決定します
これを複雑にしており、それを克服する方法がわかりません。複数のユーザーがこの関連テーブルにレコードを持つことができるということです。したがって、完全な要件は、関連レコードが存在しないレコードを返すことですが、ログインしているユーザーのレコードのみをカウントすることです。
関連する 2 つのオブジェクトは次のとおりです。
SurveyQuestion HAS_MANY AnsweredQuestion
AnsweredQuestion テーブルには次の列があります。
ID - 調査質問 ID - ユーザー 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();
2 つのコードは、子テーブルがクリアされても結果を返しません。
アプローチや実行において、私が間違っている場所を誰かが見つけることができますか?
どうもありがとう、
ニック
アップデート
要求に応じて、実行される sql ステートメントを次に示します。関連するのは 2 番目の 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))