public function afterSave() { if (!$this->owner->isNewRecord) { $this->beforeDelete(); } $data = \Yii::$app->request->post($this->owner->formName()); if (isset($data[static::$formName]) && !empty($data[static::$formName])) { $tags = $data[static::$formName]; $tagIndexs = []; foreach ($tags as $name) { if (!($tag = Tag::findOne(['name' => $name]))) { $tag = new Tag(['name' => $name]); } $tag->frequency++; if ($tag->save()) { $updatedTags[] = $tag; $tagIndexs[] = [$this->getEntityClass(), $this->getEntityId(), $tag->tag_id]; } } if (count($tagIndexs)) { \Yii::$app->db->createCommand()->batchInsert(TagIndex::tableName(), ['entity', 'entity_id', 'tag_id'], $tagIndexs)->execute(); $this->owner->populateRelation('tags', $updatedTags); } } }