【问题标题】:Laravel - getting the count from two pivot tables as one numberLaravel - 从两个数据透视表中获取计数作为一个数字
【发布时间】:2016-07-13 11:41:29
【问题描述】:

我有一个包含articles 的表和两个数据透视表viewsvotes,用于包含article_iduser_id 列的文章。对于文章,我有一个专栏publish,在那里我检查文章是否已发布。我需要按受欢迎程度进行查询,在其中我从两个数据透视表中获取所有已发表文章及其计数,其中表votescounts 中的每个投票为3,每个表中的计数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;

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

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

    $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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2021-02-06
      相关资源
      最近更新 更多