Yii determining existence of related models

2019-05-30 04:45发布

问题:

I want to run a findAll query that that only returns records where a related record doesn't exist.

Can anyone tell me how this is done in Yii?

Just a little bit of context in case it helps-

I'm working on a survey application, the objects I'm working with are-

QuestionSurvey AnsweredQuestion

SurveyQuestion HAS_MANY AnsweredQuestion

I therefore want to return QuestionSurvey models where no related AnsweredQuestion exists.

Thanks in advance,

Nick

回答1:

If you SurveyQuestion::model()->with('AnsweredQuestion')->findAll() this will happen automatically. Because it will pull all the records down together joined by an INNER JOIN (unless you tell it otherwise) and it will therefore not pull any questions down if they have no answers.

...I think.

Update
OK from your comments, I got it wrapped around my head. You actually want to view all the SurveyQuestions where AnsweredQuestions don't exist for it. In which case you want Yii to perform a LEFT JOIN which will pull down a NULL record for the joined table if a row doesn't exists. Then you need to add a condition to the relationship which states where AnsweredQuestion.id is NULL (Or whatever your primary key is, actually can be any field but primary key is good practice).

If this is a single instance kind of thing as opposed to a more permanent relationship then you can do:

SurveyQuestion::model()->with(array(
    'AnsweredQuestion'=>array(
        'joinType'=>'LEFT JOIN', 
        'condition'=>'`AnsweredQuestion`.`id` is NULL')
    )->findAll();