Laravel-将两个数据透视表中的计数作为一个数字获取


Laravel - getting the count from two pivot tables as one number

我有一个包含articles和两个数据透视表的表,viewsvotes用于具有article_id列和user_id列的文章。对于文章,我有一个专栏publish我检查文章是否已发表。我需要按受欢迎程度进行查询,其中我从两个数据透视表中获取所有已发布的文章及其计数,其中表中的每张投票votes counts3,表中的每张计数views counts1。不知道该怎么做,我以前有一个查询,我得到的只是投票的已发表文章,但我只得到一些投票的文章,而不是那些已经发表但没有投票的文章。在新查询中,我还需要添加视图,并更改计数逻辑以及包括已发布的文章而不是视图,并按这两个数据透视表中的计数对它们进行排序。

因此,所需的输出如下所示:

[{"id":117,"popularityCount":17},{"id":118,"popularityCount":15},{"id":121,"popularityCount":13}]

这是查询,但这不是我不再需要的:

$articles = DB::table('articles')
        ->select([DB::raw('articles.id'), DB::raw('COUNT(*) as "votes"')])
        ->join('votes', 'article_id', '=', 'articles.id')
        ->where('articles.publish', 1)
        ->groupBy('votes.article_id')
        ->orderBy('votes', 'desc')
        ->get();
        return $articles;

如果将来有人需要它,这就是最终对我有用的!

$result = Article::select('articles.*', 'v.vote_count', 'vw.view_count')
            ->where('publish', 1)
            ->leftJoin(DB::raw('(SELECT votes.article_id, COUNT(*) AS vote_count FROM votes GROUP BY votes.article_id) v'), 'v.article_id', '=', 'articles.id')
            ->leftJoin(DB::raw('(SELECT views.article_id, COUNT(*) AS view_count FROM views GROUP BY views.article_id) vw'), 'vw.article_id', '=', 'articles.id')
            ->orderByRaw('(v.vote_count * 3) + vw.view_count DESC')
            ->where('created_at', '>', $date->format('Y-m-d') . ' 00:00:00')
            ->get();