/** * Save product variants * @param ShopProduct $model */ protected function processVariants(ShopProduct $model) { $dontDelete = array(); if (!empty($_POST['variants'])) { foreach ($_POST['variants'] as $attribute_id => $values) { $i = 0; foreach ($values['option_id'] as $option_id) { // Try to load variant from DB $variant = ShopProductVariant::model()->findByAttributes(array('product_id' => $model->id, 'attribute_id' => $attribute_id, 'option_id' => $option_id)); // If not - create new. if (!$variant) { $variant = new ShopProductVariant(); } $variant->setAttributes(array('attribute_id' => $attribute_id, 'option_id' => $option_id, 'product_id' => $model->id, 'price' => $values['price'][$i], 'price_type' => $values['price_type'][$i], 'sku' => $values['sku'][$i]), false); $variant->save(false, false, false); array_push($dontDelete, $variant->id); $i++; } } } if (!empty($dontDelete)) { $cr = new CDbCriteria(); $cr->addNotInCondition('id', $dontDelete); $cr->addCondition('product_id=' . $model->id); ShopProductVariant::model()->deleteAll($cr); } else { ShopProductVariant::model()->deleteAllByAttributes(array('product_id' => $model->id)); } }
/** * Copy product variants * * @param ShopProduct $original * @param ShopProduct $copy */ public function copyVariants(ShopProduct $original, ShopProduct $copy) { $variants = $original->variants; if (!empty($variants)) { foreach ($variants as $v) { $record = new ShopProductVariant(); $record->product_id = $copy->id; $record->attribute_id = $v->attribute_id; $record->option_id = $v->option_id; $record->price = $v->price; $record->price_type = $v->price_type; $record->sku = $v->sku; $record->save(); } } }