Eloquent WHERE NOT 关系
Eloquent WHERE NOT with relationships
我正在使用 Lumen,它是具有模型关系的模型。我想要做的是获取所有类别并计算每个类别有多少帖子,这工作正常。但是,我不想让它统计那些creator_id == $current_user_id
,我应该怎么做呢?
这是我的 Post class:
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
这是我的分类 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();
尝试使用以下行:
$categories = Category::withCount(['posts' => function($query) use($user_id){
$query->where('creator_id', '!=', $user_id);
}])->get();
我正在使用 Lumen,它是具有模型关系的模型。我想要做的是获取所有类别并计算每个类别有多少帖子,这工作正常。但是,我不想让它统计那些creator_id == $current_user_id
,我应该怎么做呢?
这是我的 Post class:
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
这是我的分类 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();
尝试使用以下行:
$categories = Category::withCount(['posts' => function($query) use($user_id){
$query->where('creator_id', '!=', $user_id);
}])->get();