Could soomeone explain me how to build reations many to many. I cant find the proper way.
Is there problem with this database? because CRUD generated me relation only for category_product
all relations i post here i have made myself, but it dosent work anyway.
Blog is lacking of this kind relation, so i cant find good example… i found example in documentation but it is lacking for full example…
CREATE TABLE category (
id BIGINT AUTO_INCREMENT,
parent_id INT UNSIGNED DEFAULT '0' NOT NULL,
category_name VARCHAR(32) NOT NULL,
PRIMARY KEY(id),
UNIQUE(category_name)
) DEFAULT CHARACTER SET utf8 ENGINE = INNODB;
CREATE TABLE product (
id BIGINT AUTO_INCREMENT,
product_name VARCHAR(150) NOT NULL,
PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8 ENGINE = INNODB;
CREATE TABLE category_product (
category_id BIGINT COMMENT 'CONSTRAINT FOREIGN KEY (category_id) REFERENCES category(id)',
product_id BIGINT COMMENT 'CONSTRAINT FOREIGN KEY (product_id) REFERENCES product(id)',
INDEX (category_id),
INDEX (product_id),
PRIMARY KEY(category_id, product_id)
) DEFAULT CHARACTER SET utf8 ENGINE = INNODB;
ProductController.php
public function actionView()
{
$this->render('view',array(
'model'=>$this->loadModel(),
));
}
public function loadModel()
{
if($this->_model===null)
{
if(isset($_GET['id']))
$this->_model=product::model()->with('category')->together()->findbyPk($_GET['id']);
if($this->_model===null)
throw new CHttpException(404,'The requested page does not exist.');
}
return $this->_model;
}
Now snippet from model:
For category:
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(
'product'=>array(self::MANY_MANY, 'product',
'category_product(category_id, product_id)'),
);
}
for product:
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(
'category'=>array(self::MANY_MANY, 'category',
'category_product(product_id, category_id)'),
);
}
for category_product relation is empty
now in action show in template how i can access those values? Is this right?
$model->category->category_name