I
I
Ilya Beloborodov2016-01-08 14:39:02
Yii
Ilya Beloborodov, 2016-01-08 14:39:02

Yii2. How to select through a linked table?

There are three tables

CREATE TABLE `c_site` (
  `id_site` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `site_domain` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id_site`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `c_category` (
  `id_category` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name_ru` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id_category`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;

CREATE TABLE `c_category_join_site` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `id_site` int(11) DEFAULT NULL,
  `id_category` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

How to link c_category to c_site via c_category_join_site ?
In yii1, I somehow figured it out quickly, there is through .
And then I tried this
// model Category
public function getSites(){
        return $this
                ->hasMany(Site::className(),['id_site'=>'id_category'])
                ->viaTable('c_category_join_site', ['id_category' => 'id_category']);
    }

No mistakes. Selects categories, but no sites

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LAV45, 2016-01-11
@LAV45

And you would try to generate your model through Gii

public function getSites() {
    return $this
        ->hasMany(Site::className(),['id_site'=>'id_site']) // !!!
        ->viaTable('c_category_join_site', ['id_category' => 'id_category']);
}

PS in c_category_join_site the id field is unnecessary for you. It can be removed, and in its place you need to add pk in two fields ( id_site , id_category ).
By the way, it's not a good idea for an entity to name the pk field with the table name included, it's better to use the standard name id .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question