Laravel Eloquent按关系列过滤

时间:2013-12-27 13:48:23

标签: orm laravel-4 eloquent

使用Eloquent ORM我的模型设置如下:Post belongsToMany Category

post.php中

public function categories()
{
    return $this->belongsToMany('Category', 'posts_categories');
}

我想按类别关系的列过滤帖子。

所以我想做点什么:

$posts->where('categories.slug', '=', Input::get('category_slug'));

但这不起作用。

我也尝试过:

$with['categories'] = function($query){ 
    $query->where('slug', '=', Input::get('category_slug'));
};

$posts::with($with)->get();

但我认为这是为了过滤不按类别过滤的类别。

有人能告诉我这个方法吗?

1 个答案:

答案 0 :(得分:44)

我现在无法访问我的Vagrant盒子,但我相信这应该可行:

$posts = Post::whereHas('categories', function($q)
{
    $q->where('slug', '=', Input::get('category_slug'));

})->get();