Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将mysql查询转换为laravel查询生成器?_Mysql_Sql_Laravel - Fatal编程技术网

如何将mysql查询转换为laravel查询生成器?

如何将mysql查询转换为laravel查询生成器?,mysql,sql,laravel,Mysql,Sql,Laravel,我有两个表,第一个注释和文章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

我有两个表,第一个注释和文章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
您正在使用“finisher”,这意味着
->count('comments.id')
不再返回
QueryBuilder
的实例,而是返回常规类型(
integer

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

您肯定知道其他的finisher,如
->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();
请尝试此操作,如果您仍然面临任何问题,请告诉我。

“selectRaw()必须是array,string given类型”再次出现错误
DB::table('comments')
->join('news', 'news.id', '=', ' comments.article_id')
->selectRaw('comments.article_id', 'news.title', ' news.category_id', 'count(comments.id) as countsxyz')
->groupBy('article_id')
->orderBy(DB::raw('countsxyz'), 'desc')
->limit(3)
->get();