You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel:如何用withCount()统计帖子的作者与访客评论数

问题:如何通过withCount统计帖子的作者评论数和访客评论数?

我有Post与Comment的hasMany关联关系,模型代码如下:

class Post extends Model
{
    // @property int $id
    // @property string $title
    // @property string $user_id

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}


class Comment extends Model
{
    // @property int $id
    // @property int $post_id
    // @property int $user_id (author ids + guests ids)
    // @property string $content

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

帖子包含作者评论和访客评论,评论表的user_id字段同时存储作者ID和访客ID。需要获取帖子列表时,同时预加载作者评论数(如author_comments_count = 2)和访客评论数(如guests_comments_count = 3),请问如何使用withCount()实现?


解决方案

可以通过在withCount中为关联关系设置别名,并传入闭包添加过滤条件,直接在数据库层面完成统计:

$posts = Post::query()
    ->withCount([
        // 统计当前帖子作者的评论数
        'comments as author_comments_count' => function ($query) {
            $query->whereColumn('comments.user_id', 'posts.user_id');
        },
        // 统计访客的评论数(非帖子作者的评论)
        'comments as guests_comments_count' => function ($query) {
            $query->whereColumn('comments.user_id', '!=', 'posts.user_id');
        }
    ])
    ->get();

说明:

  • 使用as 别名的方式自定义统计结果的属性名,后续可通过$post->author_comments_count和$post->guests_comments_count直接访问
  • whereColumn用于关联两张表的字段,确保过滤条件在数据库层面执行,性能更优
  • 如果访客评论的定义是user_id为特定值(如null),可调整闭包内的条件,例如:
    'comments as guests_comments_count' => function ($query) {
        $query->whereNull('comments.user_id');
    }
    

内容的提问来源于stack exchange,提问作者Dmitrijs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 19:40:58