Answer the question
In order to leave comments, you need to log in
Am I doing relations correctly in yii?
Good afternoon. There are 3 tables, without foreign keys.
For a long time I suffered with relations in yii, I could not figure out how to connect them without FK. In theory, I wanted to make a many-many connection on both sides for universality, but since I still display 1 category per page, I decided that it was superfluous, and made the link "one category - many pages".
The questions are:
class Pages extends CActiveRecord
{
public function relations()
{
return array(
// pivot.page_id = pages.id
'pivot' => array(self::HAS_ONE, 'PageCategoryPivot', array('page_id' => 'id')),
// pivot.cat_id = category.id, 2 вопрос про эту строку:
'category' => array(self::BELONGS_TO, 'Category', array('cat_id' => 'id'), 'through' => 'pivot'),
);
}
}
class PageCategoryPivot extends CActiveRecord
{
public function relations()
{
return array(
'page' => array(self::HAS_ONE, 'Pages', 'page_id'),
'category' => array(self::HAS_ONE, 'Category', 'cat_id')
);
}
}
class Category extends CActiveRecord
{
public function relations()
{
return array(
// pivot.cat_id = category.id
'pivot' => array(self::HAS_ONE, 'PageCategoryPivot', array('cat_id' => 'id')),
// pivot.page_id = pages.id
'pages' => array(self::HAS_MANY, 'Pages', array('page_id' => 'id'), 'through' => 'pivot')
);
}
}
Answer the question
In order to leave comments, you need to log in
Here, if there is an intermediate table with the IDs of the other two, then the MANY-MANY connection would otherwise make no sense in such a table, from the office. here is the documentation:
'categories'=>array(self::MANY_MANY, 'Category', 'tbl_post_category(post_id, category_id)'),
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question