Hi, I stumbled over this topic by chance (I was actually just trying to output the results from many to many joins … I thought List View should do this automagically)
Then however I was interested in the solution of this problem. Here it goes:
(I used my tables: Task, task_questions, Question)
Model Relations:
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(
'questions'=>array(self::MANY_MANY, 'Question', 'task_questions(taskId, questionId)'),
);
}
Controller:
$criteria=new CDbCriteria;
$criteria->with=array(
'questions' => array(
//Select=false gives me all questions. It can happen that you don't get all questions when you have conditions. Fun fact: Select=false actually adds a distinct Select.
'select' => false,
),
);
//All questions that have 2,8 or both
$criteria->condition = 'questions.Id in (2,<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/cool.gif' class='bbc_emoticon' alt='8)' />';
$criteria->group = 't.id';
//Only tasks that have both of them
$criteria->having = 'COUNT(DISTINCT questions.id) = 2';
//Together is important for where statements / conditions
$criteria->together = true;
$dataProvider=new CActiveDataProvider('Task', array('criteria' => $criteria));
And in the view, you can loop over the results (depends on how you access your dataProvider).
And this is how you get all tasks that have questions with the ids 2 and 8. You don’t get questions that have either 2 or 8. You get however, tasks that have 2, 8 and x other questions. And since I don’t want to bother the guys at StackOverflow again, I have to leave it at that. (This is actually just a MySQL problem).
You can do this with HAS::MANY THROUGH relations, too.