Im trying to create a simple website to display synonyms and antonyms but im getting confuse with relationships.
My sql tables the following:
CREATE TABLE IF NOT EXISTS `word` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`word` varchar(200) NOT NULL,
`slug` varchar(150) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `word` (`word`),
KEY `slug` (`slug`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=25108 ;
CREATE TABLE IF NOT EXISTS `synonyms` (
`lookup_id` int(11) NOT NULL COMMENT 'CONSTRAINT FOREIGN KEY(lookup_id) REFERENCES word(id))',
`related_id` int(11) NOT NULL COMMENT 'CONSTRAINT FOREIGN KEY(related_id) REFERENCES word(id))',
KEY `lookup_id` (`lookup_id`),
KEY `related_id` (`related_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `antonyms` (
`lookup_id` int(11) NOT NULL COMMENT 'CONSTRAINT FOREIGN KEY(lookup_id) REFERENCES word(id))',
`related_id` int(11) NOT NULL COMMENT 'CONSTRAINT FOREIGN KEY(related_id) REFERENCES word(id))',
KEY `lookup_id` (`lookup_id`),
KEY `related_id` (`related_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
My relationships are declared like:
class Word ..{
...
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(
'antonyms' => array(self::HAS_MANY, 'Antonyms', 'related_id'),
'antonyms1' => array(self::HAS_MANY, 'Antonyms', 'lookup_id'),
'synonyms' => array(self::HAS_MANY, 'Synonyms', 'related_id'),
'synonyms1' => array(self::HAS_MANY, 'Synonyms', 'lookup_id'),
);
}
....
}
class Synonyms ... {
.....
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(
'related' => array(self::BELONGS_TO, 'Word', 'related_id'),
'lookup' => array(self::BELONGS_TO, 'Word', 'lookup_id'),
);
}
......
}
Is this the proper and optimized way to do it?
When i search a word i want to show all synonyms , for that i crated this function
public function getSynonyms($lookup_id)
{
$model = Synonyms::model()->findAll('lookup_id=:lookup_id', array(':lookup_id' => $lookup_id));
return $model;
}
That i use on my view action like:
public function actionView($word)
{
$model = $this->loadModelBySlug($word);
$this->render('view',array(
'model'=> $model,
'sinonimos' => $this->getSynonyms($model->id),
));
}
And finally on my view i display synonyms like this:
foreach ($sinonimos as $sinonimo)
{
var_dump($sinonimo->related->word);
}
All these is working but something inside me says im not doing it well… Any help¿ Thanks!!!