CREATE TABLE IF NOT EXISTS `topic` (
`topic` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`area_name` smallint(6) NOT NULL DEFAULT '0',
PRIMARY KEY (`topic`)
)
CREATE TABLE IF NOT EXISTS `topic_link` (
`parent` int(11) NOT NULL DEFAULT '0',
`child` int(11) NOT NULL DEFAULT '0'
)
Basically, one topic can have N children, which in turn, can have their own children. I’m a bit confused on how to create the relations in the respective models.
I’ve created the following Topic model:
class Topic extends CActiveRecord {
public function relations() {
return array(
'parent' => array(self::BELONGS_TO, 'TopicLink', 'parent'),
'children' => array(self::HAS_MANY, 'TopicLink', 'child'),
);
}
}
But have no idea on how to create the Topic_Link model.
It looks like a MANY_MANY relation where you don’t need a model for the junction table. Remember to define a composite primary key holding both columns in the ‘topic_link’ table.
Also I would suggest a naming convention, where primary keys are always named ‘id’ and foreign keys are named ‘table_id’ where ‘table’ is a singular form of the referred table name. The FK may contain a prefix to suggest the relation meaning, like ‘parent_topic_id’.
Oh thanks, it helped, but I’m still not able to get the children of a specific topic.
This is what I did:
class Topic extends CActiveRecord {
public function relations() {
return array(
'children' => array(self::MANY_MANY, 'TopicLink', 'topic_link(parent, child)'),
);
}
}
class TopicLink extends CActiveRecord{
public function primaryKey(){
return array('parent', 'child');
}
public function relations() {
return array();
}
}
By doing so, when I iterate over the children of a topic, I get all the subsubtopics, not the immediate subtopics. For example,