/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Category::find(); // Подзапрос для получения количества статей в категориях и возможности сортировки по этому параметру $subQuery = Post::find()->select('category_id, count(id) as post_count')->groupBy('category_id'); $query->leftJoin(['postsNum' => $subQuery], 'postsNum.category_id = id'); $query->select('{{%category}}.*, postsNum.post_count'); $dataProvider = new ActiveDataProvider(['query' => $query]); /** * Setup your sorting attributes * Note: This is setup before the $this->load($params) * statement below */ $dataProvider->setSort(['attributes' => ['id', 'parent_id', 'name', 'url', 'category_art', 'add_method', 'postCount' => ['asc' => ['postsNum.post_count' => SORT_ASC], 'desc' => ['postsNum.post_count' => SORT_DESC], 'label' => 'Order Name']]]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // filter by order amount $query->andFilterWhere(['postsNum.post_count' => $this->postCount]); $query->andFilterWhere(['id' => $this->id, 'parent_id' => $this->parent_id, 'post_num' => $this->post_num, 'category_art' => $this->category_art]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'url', $this->url])->andFilterWhere(['like', 'icon', $this->icon])->andFilterWhere(['like', 'description', $this->description])->andFilterWhere(['like', 'meta_title', $this->meta_title])->andFilterWhere(['like', 'meta_descr', $this->meta_descr])->andFilterWhere(['like', 'meta_keywords', $this->meta_keywords])->andFilterWhere(['like', 'post_sort', $this->post_sort])->andFilterWhere(['like', 'short_view', $this->short_view])->andFilterWhere(['like', 'full_view', $this->full_view])->andFilterWhere(['like', 'header', $this->header])->andFilterWhere(['like', 'footer', $this->footer])->andFilterWhere(['like', 'header', $this->add_method]); return $dataProvider; }
/** * Возвращает список всех категорий статей * * Обращение к БД происходит только при первом вызове метода. Результат записывается в params. * При последующих вызовах метода, результат берется из свойства params. * * @return array Список категорий в виде массива, индексированного по id категории */ public static function getCategories() { if (!isset(Yii::$app->params['categories']) || empty(Yii::$app->params['categories'])) { // Получаем из базы все категории и переиндексируем по ID Yii::$app->params['categories'] = ArrayHelper::index(Category::find()->asArray()->all(), 'id'); } return Yii::$app->params['categories']; }
/** * Finds the Category model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return Category the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Category::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * @return \yii\db\ActiveQuery */ public function getCategory() { return $this->hasOne(Category::className(), ['id' => 'category_id']); }