计算来自同一模型的多个模型的关系

时间:2020-07-07 09:47:05

标签: laravel

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

我想做的是:

  • 获取属于特定用户的所有帖子中所有评论的数量
  • 获取属于同一用户的所有帖子中本月所有评论的数量
  • 起点是特定的ID帖子(因此,不是从用户ID开始)。

请在下面查看我现在拥有的东西,并且可以使用。

我的问题是:是否可以将执行-> 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');

1 个答案:

答案 0 :(得分:0)

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

在您的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();