frontend\modules\topic\models\Topic::addTags PHP Method

addTags() public method

添加标签
public addTags ( array $tags ) : boolean
$tags array
return boolean
    public function addTags(array $tags)
    {
        $return = false;
        $tagItem = new PostTag();
        foreach ($tags as $tag) {
            $_tagItem = clone $tagItem;
            $tagRaw = $_tagItem::findOne(['name' => $tag]);
            if (!$tagRaw) {
                $_tagItem->setAttributes(['name' => $tag, 'count' => 1]);
                if ($_tagItem->save()) {
                    $return = true;
                }
            } else {
                $tagRaw->updateCounters(['count' => 1]);
            }
        }
        return $return;
    }

Usage Example

 /**
  * 新建话题
  * @return mixed
  */
 public function actionCreate()
 {
     $model = new Topic();
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $topService = new TopicService();
         if (!$topService->filterContent($model->title) || !$topService->filterContent($model->content)) {
             $this->flash('请勿发表无意义的内容', 'warning');
             return $this->redirect('create');
         }
         $model->user_id = Yii::$app->user->id;
         $model->type = 'topic';
         if ($model->tags) {
             $model->addTags(explode(',', $model->tags));
         }
         if ($model->save()) {
             (new UserMeta())->saveNewMeta('topic', $model->id, 'follow');
             // 更新个人总统计
             UserInfo::updateAllCounters(['post_count' => 1], ['user_id' => $model->user_id]);
             $this->flash('发表文章成功!', 'success');
             return $this->redirect(['view', 'id' => $model->id]);
         }
     } else {
         return $this->render('create', ['model' => $model]);
     }
 }