首页 > 解决方案 > 如何将 mysql 查询转换为 laravel 查询生成器?

问题描述

我有 2 个表格,在第一条评论和文章 id 中,在第二篇文章标题中,id ,文章类别。我想要一个评论最多的文章标题。

SELECT comments.article_id, news.title, news.category_id,
    COUNT(comments.id) as counts 
  FROM comments 
  JOIN news ON news.id = comments.article_id 
  GROUP BY(article_id) 
  ORDER BY counts DESC 
  LIMIT 3

我试过这个:

  $articles = DB::table('comments')
        ->join('news', 'news.id', '=', ' comments.article_id')
        ->select(comments.article_id', 'news.title', ' news.category_id')
        ->count('comments.id')
        ->groupBy('article_id')
        ->orderBy(DB::raw('count(comments.id)', 'desc')
        ->limit(3)
        ->get();

但是有:

Call to a member function groupBy() on integer

标签: mysqlsqllaravel

解决方案


您正在使用“整理器”,这意味着->count('comments.id')不再返回QueryBuilder常规类型 ( integer) 的实例。

由于integers在 PHP 中不是类,您试图在非类上执行方法,这导致显示此错误消息。

您肯定知道其他终结者,例如->sum(), ->all(), ->get(), ...

只需删除您的线路->count('comments.id'),您就可以开始了:

$articles = DB::table('comments')
  ->join('news', 'news.id', '=', ' comments.article_id')
  ->select('comments.article_id', 'news.title', ' news.category_id')
  ->groupBy('article_id')
  ->orderBy(DB::raw('count(comments.id)', 'desc')
  ->limit(3)
  ->get();

推荐阅读