【问题标题】:Eloquent WHERE NOT with relationships雄辩的 WHERE NOT 与关系
【发布时间】: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


    【解决方案1】:

    尝试使用以下行:

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

    【讨论】:

    • 谢谢,它确实有效。但是这样使用它安全吗?我在一些 Laracast 的论坛帖子中看到你不应该那样做。我可能错了,如果我错了,请纠正我。
    • 随意使用此方法。这是正确的做法
    猜你喜欢
    • 2014-11-09
    • 2021-05-29
    • 2015-02-07
    • 2017-05-19
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多