C
C
ColdSpirit2015-06-26 16:53:03
MySQL
ColdSpirit, 2015-06-26 16:53:03

Am I doing relations correctly in yii?

Good afternoon. There are 3 tables, without foreign keys.
1881441e6e32431c8a4f0fc173f6a254.PNG
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:

  1. I can not understand what type to make a connection with Pivot. Pages-Pivot is most likely HAS_ONE, but what about categories?
  2. When I use 'through', let's say in the Pages model, does the code in the 'category' relationship mean that Pages BELONGS-TO Category or 'pivot' BELONGS-TO Category?
  3. Why does the application give an error when I remove PK from the intermediate (not only) table? I have specified all the data for communication, but the program cannot find these columns. Really communication without PK is impossible?
  4. As I understand it, writing on these links does not work - only reading, writing and deleting need to be added to the model with pens, right?
  5. Did I do everything correctly / described the code in the comments? If not, please let me know how.

The code is working, but I doubt about its "correctness".
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

1 answer(s)
E
Evgeny Bukharev, 2015-06-26
@evgenybuckharev

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 question

Ask a Question

731 491 924 answers to any question