/** * @param $alias * @return null|static * @throws NotFoundHttpException */ protected function findCategoryWithAlias($alias) { $category = Category::findOne(['alias' => $alias]); if ($category == null) { throw new NotFoundHttpException(Yii::t('app', 'Category not found')); } return $category; }
/** * @param Category $category * @return array */ public function findPostsWithCategory(Category $category) { $subCategories = Category::findAll(['category.parentId' => $category->id]); $ids = [$category->id]; foreach ($subCategories as $subCategory) { $ids[] = $subCategory->id; } $query = $this->find(); $query->orderBy('category.sort'); $query->andWhere(['in', 'post.categoryId', $ids]); if (!$this->validate()) { return []; } $query->andFilterWhere(['like', 'title', $this->query])->andFilterWhere(['like', 'content', $this->query]); $items = []; foreach ($query->all() as $post) { /* @var $post Post */ $items[$post->category->alias]['category'] = $post->category; $items[$post->category->alias]['posts'][] = $post; } return $items; }
public function run() { $categories = Category::find()->joinWith(['posts'])->addSelect(['category.*', 'count(post.id) as postCount'])->groupBy('category.id')->all(); echo $this->renderCategories($categories, null, 0); }