public function insertCategories($categoryIds, $beforeCount = true, $afterCount = true) { if (!is_array($categoryIds)) { return false; } $categoryIds = array_unique($categoryIds); $this->deleteCategories($beforeCount); //先删除文章分类 //插入新分类 if ($categoryIds) { foreach ($categoryIds as $v) { if (!Category::find()->andWhere('mid=:mid', [':mid' => $v])->one()) { continue; } $model = new Relationship(); $model->cid = $this->cid; $model->mid = $v; $model->insert(false); if ($afterCount) { //更新分类文章数 Category::updateAllCounters(['count' => 1], ['mid' => $v]); } } } return true; }
/** * После сохранения модели необходимо переопределить родителей, пересчитать кол-во у категорий и прикрепленные картинки * @param bool $insert * @param array $changedAttributes */ public function afterSave($insert, $changedAttributes) { // Удаляем все связи if (!$insert) { $this->unlinkAll('categories', true); } // Связываем с категориями if (is_array($this->parents)) { foreach ($this->parents as $parent) { // Устанавливает родительские категории $category = Category::findOne($parent); // Добавляем связь $this->link('categories', $category); } } // Уменьшаем кол-во у старых категорий if (is_array($this->parentsCache)) { Category::updateAllCounters(['cnt_products' => -1], ['id' => $this->parentsCache]); } // Увеличиваем кол-во у новых категорий $new_parents = $this->getAllCategoriesId(); Category::updateAllCounters(['cnt_products' => 1], ['id' => $new_parents]); // Удаляем все теги $this->removeAllTagValues(); // Сохраняем новые $this->addTagValues(['bar', 'baz']); parent::afterSave($insert, $changedAttributes); }