/** * Set product categories and main category * @param array $categories ids. * @param integer $main_category Main category id. */ public function setCategories(array $categories, $main_category) { $dontDelete = array(); if (!ShopCategory::model()->countByAttributes(array('id' => $main_category))) { $main_category = 1; } if (!in_array($main_category, $categories)) { array_push($categories, $main_category); } foreach ($categories as $c) { $count = ShopProductCategoryRef::model()->countByAttributes(array('category' => $c, 'product' => $this->id)); if ($count == 0) { $record = new ShopProductCategoryRef(); $record->category = (int) $c; $record->product = $this->id; $record->switch = $this->switch; // new param $record->save(false, false, false); } $dontDelete[] = $c; } // Clear main category ShopProductCategoryRef::model()->updateAll(array('is_main' => 0, 'switch' => $this->switch), 'product=:p', array(':p' => $this->id)); // Set main category ShopProductCategoryRef::model()->updateAll(array('is_main' => 1, 'switch' => $this->switch), 'product=:p AND category=:c', array(':p' => $this->id, ':c' => $main_category)); // Delete not used relations if (sizeof($dontDelete) > 0) { $cr = new CDbCriteria(); $cr->addNotInCondition('category', $dontDelete); ShopProductCategoryRef::model()->deleteAllByAttributes(array('product' => $this->id), $cr); } else { // Delete all relations ShopProductCategoryRef::model()->deleteAllByAttributes(array('product' => $this->id)); } }