I’m dealing with a many to many relationships.
These are my tables:
Issue (id, title, description)
Topic (id, title)
Issue_Topic (id, issue_id, topic_id)
So now I’m trying to find all the Issues for a given Topic.
My relation is as follows:
Issue.php > relations()
'topics'=>array(self::MANY_MANY, 'Topic', 'Issue_Topic(issue_id, topic_id)'),
This works fine for the Issue.actionShow() method where I say:
$models = Issue::model()->with('topics')->findByPk($id);
Now, I’m going for a list of Issues that belong to a particular topic. I was imagining it working something akin to:
$models = Issue::model()->with('topics')->findByAttributes( /* topic.id = $id OR Issue_Topic.topic_id = $id */ );
I cannot get the above to work. I keep getting the error message about topic.id is not a field of the issue table.
I have found a way that I can accomplish what I want, but it seems like Yii’s relationship handling should be able to deal with this.
This is what I have that works, which I want to not do.
$criteria = new CDbCriteria;
$criteria->join = 'inner join issue_topic on issue.id=issue_topic.issue_id inner join topic on issue_topic.topic_id=topic.id';
$criteria->condition = 'topic.id='.$tid;
$models = Issue::model()->findAll($criteria);
It seems crazy to me to have to define this relationship when it’s already there in the issue model. What am I missing here? What is the way to do findAllByAttributes where the attribute is on the related table?