Eloquent WHERE NOT with relationship

时间:2017-10-07 09:56:43

标签: php laravel eloquent lumen

我正在使用Lumen及其模型与模型的关系。我想要做的是获取所有类别并计算每个类别有多少帖子,这是正常的。但是,我不希望它计算那些creator_id == $current_user_id,我应该怎么做?

这是我的Post课程:

public function user(){
        return $this->belongsTo(User::class);
}

public function category(){
        return $this->belongsTo(Category::class);
}

这是我的分类:

public function posts(){
        return $this->hasMany(Post::class);
}

这是我的疑问:

public function getCategories($user_id){
        $categories = Category::withCount('posts')->get();
        return new JsonResponse(['categories' => $categories]);
}

所以我不想计算当前用户创建的帖子。

所以输出应该是这样的:

{
    "categories": [
        {
            "name": "All",
            "posts_count": 0
        }]
}

这也是我没有成功的尝试:

$categories = Category::where('creator_id', '!=', $user_id)->withCount('posts')->get();

1 个答案:

答案 0 :(得分:1)

尝试使用以下行:

$categories = Category::withCount(['posts' => function($query) use($user_id){
   $query->where('creator_id', '!=', $user_id);
}])->get();