public function search($params) { $query = Tag::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $this->addCondition($query, 'id'); $this->addCondition($query, 'title', true); $this->addCondition($query, 'description', true); $this->addCondition($query, 'frequency'); return $dataProvider; }
/** * Updates an existing Blog model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $items = []; foreach ($model->getTags()->all() as $item) { $items[] = $item->title; } $model->tagged = implode(', ', $items); if ($model->load(Yii::$app->request->post()) && $model->save()) { $tags = array_unique(preg_split('/\\s*,\\s*/u', preg_replace('/\\s+/u', ' ', is_array($model->tagged) ? implode(',', $model->tagged) : $model->tagged), -1, PREG_SPLIT_NO_EMPTY)); $removed = array_diff($items, $tags); foreach (Tag::find()->where(['in', 'title', $removed])->all() as $removedItem) { BlogTag::deleteAll(['blog_id' => $model->id, 'tag_id' => $removedItem->id]); $removedItem->frequency--; $removedItem->save(); } $added = array_diff($tags, $items); $rows = []; foreach ($added as $title) { $tag = Tag::findOne(['title' => $title]); if (!$tag) { $tag = new Tag(); $tag->title = $title; } $tag->frequency++; if (!$tag->save()) { Yii::error("Cannot save tag " . $tag->title . json_encode($tag->getErrors())); continue; } $rows[] = [$model->id, $tag->id]; } if (!empty($rows)) { $model->getDb()->createCommand()->batchInsert('{{%blog_tag}}', ['blog_id', 'tag_id'], $rows)->execute(); } return $this->redirect(Yii::$app->request->referrer); } else { return $this->render('updateBlog', ['model' => $model]); } }
/** * Finds the Tag model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Tag the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if ($id !== null && ($model = Tag::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * @return \yii\db\ActiveQuery */ public function getTags() { return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('{{%blog_tag}}', ['blog_id' => 'id']); }