Answer the question
In order to leave comments, you need to log in
Yii Relations. How to select properly unique values from related table?
Good afternoon
There are 2 tables:
Product entities (reduced, there are more fields):
CREATE TABLE `goods` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`menutitle` VARCHAR(250) NOT NULL COMMENT 'Название',
PRIMARY KEY (`id`),
INDEX `menutitle` (`menutitle`),
INDEX `FK_goods_goods_brand` (`brand_id`),
CONSTRAINT `FK_goods_goods_brand` FOREIGN KEY (`brand_id`) REFERENCES `goods_brand` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3782;
CREATE TABLE `goods_variations` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`goods_id` INT(10) UNSIGNED NOT NULL,
`articul` VARCHAR(100) NULL DEFAULT NULL,
`size` VARCHAR(100) NULL DEFAULT NULL,
`color` VARCHAR(100) NULL DEFAULT NULL,
`weight` VARCHAR(100) NULL DEFAULT NULL,
`stock` INT(5) NULL DEFAULT NULL,
PRIMARY KEY (`id`),
INDEX `FK_goods_options_goods` (`goods_id`),
INDEX `articul` (`articul`),
CONSTRAINT `FK_goods_options_goods` FOREIGN KEY (`goods_id`) REFERENCES `goods` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=5060;
'variations' => array(self::HAS_MANY, 'GoodsVariations', 'goods_id'),
'goods' => array(self::BELONGS_TO, 'Goods', 'goods_id'),
$product = Goods::model()->findByPk($product_id); // Произвольный ID, например 1234, не суть
foreach($product->variations as $variation) {
echo $variation->size . '<br />'; // Пускай в таком виде
}
Answer the question
In order to leave comments, you need to log in
Since the variations link is used not only in the context of size, you need to create a separate link for this, where in the parameters you specify a selection of only unique size values, or iterate through the array
Then it's easier with an array, I still don't know Yii enough to create Relations not through the built-in GII.
In Google, all the info that I found is to do it somehow through such a construction:
public function relations() {
return array(
'variations' => array(self::HAS_MANY, 'GoodsVariations', 'goods_id', 'distinct'=>true),
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question