/** * Assigns terms to an object. * * @param integer $object_id * @param integer|array $params The ID/IDs of the term/terms that need to be assigned. Can be integer or array of integers. * @return An array with the currently assigned TaxonomyTerms. */ public function addTerm($object_id, $params) { $result = []; foreach (TaxonomyTerms::findAll((array) $params) as $term) { $data['term_id'] = $term->id; $data['object_id'] = $object_id; if (!(new Query())->from($this->table)->where($data)->exists(CategoryTerm::getDb())) { Yii::$app->db->transaction(function () use($data, $term, &$result) { CategoryTerm::getDb()->createCommand()->insert($this->table, $data)->execute(); $term->updateCounters(['total_count' => 1]); TaxonomyDef::updateAllCounters(['total_count' => 1], ['id' => $this->id]); $result[] = $term; }); } } return $result; }
/** * Add term/s with the ability to make hierarchies. * * The object_id can be skipped. In this case a hierarchy will be created without being attached to an object. * * $params can be a string or an array: * - If string, this is considered to be a root of a hierarchy; * - If array, if only filled with values, this means these are all roots of a hierarchy; * - If array and key => value is given, the key is the parent, the root is the child. * * @param integer $object_id Id to and object. Not mandatory. * @param string|array $params Terms */ public function addTerm($object_id, $params) { $cachedParents = []; $addTerm = function ($parent, $item) use($object_id, &$cachedParents) { if ($this->detectLoop($parent, $item)) { throw new InvalidCallException('Loop detected! Cannot add parent as a child!'); } $term = $this->getTaxonomyTerm($item); if (array_key_exists($parent, $cachedParents)) { $term->parent_id = $cachedParents[$parent]->id; } else { if (is_string($parent)) { $parentTerm = $this->getTaxonomyTerm($parent); $cachedParents[$parent] = $parentTerm; $term->parent_id = $parentTerm->id; } } if ($term->getDirtyAttributes(['parent_id'])) { $term->save(false); } if ($object_id) { $data['term_id'] = $term->id; $data['object_id'] = $object_id; if (!(new Query())->from($this->table)->where($data)->exists(CategoryTerm::getDb())) { Yii::$app->db->transaction(function () use($data, $term) { CategoryTerm::getDb()->createCommand()->insert($this->table, $data)->execute(); $term->updateCounters(['total_count' => 1]); TaxonomyDef::updateAllCounters(['total_count' => 1], ['id' => $this->id]); }); } } }; $params = (array) $params; foreach ($params as $parent => $item) { if (is_array($item)) { foreach ($item as $child) { $addTerm($parent, $child); } } else { $addTerm($parent, $item); } } }