In my Yii2 project I have posts table linked to categories table as many-to-many relation (posts_categories table).
In my Post model I have getByCategory($category_id) function which returns all posts of the category. In controller I have actionCategory where I use this function and pass all posts for certain category. I also have a GET form in the view for filtering my posts through GET parameter (I need this value to be contained in title or content of posts shown). The problem is I don't have an idea how to apply some filter function to my getByCategory call in controller in a smart way.
My function code:
public static function getPostsByCategory($category_id = null)
{
$posts = Post::find()
->select('posts.*')
->innerJoin('posts_categories', '`posts`.`id` = `posts_categories`.`post_id`')
->where(['posts_categories.category_id' => $category_id])
->orderBy(['date_create' => SORT_DESC])
->all();
return $posts;
}
Controller action:
public function actionCategory($id)
{
$posts = Post::getPostsByCategory($id);
return $this->render('index', array('all_posts' => $posts));
}
All my ideas like using statements like "if $_GET is not empty - use one query - if empty - another one" in controller or in model does look messy and lead to duplicating code in other actions where I'll also need my $_GET filtering. Could you please advice something? Thanks.