Answer the question
In order to leave comments, you need to log in
Yii2 how to select all articles of a specific tag?
The situation is this, there is a table of articles, a table of tags and a table of links (article id, tag id).
The task is this, you need to show all articles of a particular tag (for example, all articles of the friends tag).
Action of all articles in the controller:
public function actionArticles($tag = false)
{
// Проверяем права доступа
if (!Yii::$app->user->checkAccess('backend.blog.articles.view')) {
throw new HttpException(403, Yii::t('app', 'У Вас нет прав для работы с данным разделом!'));
}
$searchModel = new BlogSearch;
$dataProvider = $searchModel->search($_GET, $tag);
return $this->render('articles', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
public function search($params, $tag = false)
{
$query = Blog::find()->orderBy(['report' => SORT_DESC, 'date_create' => SORT_DESC ]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => Yii::$app->getModule('blog')->recordsPerPage
]
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$this->addCondition($query, 'name', true);
$this->addCondition($query, 'comm', true);
$this->addCondition($query, 'rating', true);
$this->addCondition($query, 'status', true);
$this->addCondition($query, 'report', true);
$this->addCondition($query, 'draft', true);
$this->addWithCondition($query, 'user', 'user', User::tableName() . '.username', true);
return $dataProvider;
}
protected function addCondition($query, $attribute, $partialMatch = false)
{
$value = $this->$attribute;
if (trim($value) === '') {
return;
}
if ($partialMatch) {
$query->andWhere(['like', $attribute, $value]);
} else {
$query->andWhere([$attribute => $value]);
}
}
Answer the question
In order to leave comments, you need to log in
What is the problem?
Sql-documentation - about working with MANY-TO-MANY
Yii2-documentation - about working with RAR (via, viaTable, hasMany, joinWith)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question