【发布时间】:2017-10-07 09:56:42
【问题描述】:
我正在使用 Lumen,它是具有模型关系的模型。我要做的是获取所有类别并计算每个类别有多少帖子,这很好。但是,我不希望它计算那些creator_id == $current_user_id,我该怎么做呢?
这是在我的 Post 类中:
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
这是在我的 Category 类中:
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();
【问题讨论】:
标签: php laravel eloquent lumen