如何将mysql查询转换为laravel查询生成器?
我有两个表,第一个注释和文章id,第二个文章标题,id,文章类别。我想要一篇评论最多的文章的标题如何将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
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();