Yii determining existence of related models

本小妞迷上赌 提交于 2019-12-23 01:40:11

问题


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();


来源:https://stackoverflow.com/questions/13210492/yii-determining-existence-of-related-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!