【发布时间】:2016-10-15 14:26:39
【问题描述】:
在我的 Yii2 项目中,我将posts 表链接到categories 表作为多对多 关系(posts_categories 表)。
在我的Post 模型中,我有getByCategory($category_id) 函数,它返回该类别的所有帖子。在控制器中,我有actionCategory,我在其中使用此功能并传递特定类别的所有帖子。我在视图中还有一个 GET 表单,用于通过 GET 参数过滤我的帖子(我需要此值包含在显示的帖子的标题或内容中)。问题是我不知道如何以智能的方式将某些过滤器功能应用于控制器中的 getByCategory 调用。
我的功能码:
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;
}
控制器动作:
public function actionCategory($id)
{
$posts = Post::getPostsByCategory($id);
return $this->render('index', array('all_posts' => $posts));
}
我的所有想法,例如在控制器或模型中使用“如果 $_GET 不为空 - 使用一个查询 - 如果为空 - 另一个”这样的语句,确实看起来很混乱,并导致在我还需要的其他操作中重复代码我的 $_GET 过滤。你能不能给点建议?谢谢。
【问题讨论】: