首页 > 解决方案 > 来自同一模型的多个模型的计数关系

问题描述

我有以下三个模型:用户、帖子和评论。一个用户可以有多个帖子,每个帖子可以有多个评论。

我想做的是:

请参阅下面我现在所拥有的,这很有效。

我的问题是:是否可以将执行 ->sum() 的最后两行添加到查询中?

我认为这个查询已经很漂亮了,但它看起来会更好,但更重要的是,如果最后两行也包括在内,它会使缓存变得容易得多。

$post = Post::findOrFail($id);

$posts = Post::where('user_id', $post->user_id)
        ->withCount(['comments as comments_total'])
        ->withCount([
            'comments as comments_this_month' => function ($q) {
                $q->whereBetween('created_at',
                    [ Carbon::now()->startOfMonth(), Carbon::now()->endOfMonth() ]
                );
            },
        ])->get();
});

$comments_this_month_count = $posts->sum('comments_this_month');
$comments_total_count = $posts->sum('comments_total');

标签: laravel

解决方案


我可以只用两行代码提出更好的解决方案。

在模型中定义hasManyThrough关系User

public function comments()
{
    return $this->hasManyThrough(
        Comment::class,
        Post::class,
        'user_id', // Foreign key on posts table...
        'post_id' // Foreign key on comments table...
    );
}

然后像这样调用它:

$comments_this_month_count = User::find($post->user_id)->comments()
->whereMonth('created_at', now()->month)->count();

$comments_total_count = User::find($post->user_id)->comments()->count();

推荐阅读