2017-10-07 206 views
0

我正在使用Lumen和模型与模型的关系。我试图做的是获取所有类别,并计算每个类别有多少帖子,哪些工作正常。但是,我不希望它计算哪些creator_id == $current_user_id,我该怎么做呢?雄辩不与关系

这是在我的岗位等级:

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

尝试使用以下行:

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

谢谢,它确实有效。但是像这样使用它是否安全?我在一些Laracast的论坛帖子中看到,你不应该那样做。我可能是错的,如果我是,请纠正我。 –

+0

随意使用这种方法。这是做到这一点的正确方法 –