mysql - 如何将 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
解决方案
您正在使用“整理器”,这意味着->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();
推荐阅读
- python - Python Selenium driver.get 打开空白网址
- react-native - iOS 推送通知权限未按预期触发
- c++ - QT Q3Dsurface 显示面板
- python - beautifulsoup:无法从带有 cookie 的股息投资者那里获得正确的信息
- html - 根据最长行的背景和边框换行文本 - CSS
- google-apps-script - 谷歌表格获取行中第一个和最后一个彩色单元格的地址
- python - 我们如何在 python 中找到该模式的模式和出现次数?
- laravel - 来自两个输入的 laravel 同步
- c# - Xamarin Android - 在片段中访问 textview onclick
- javascript - Javascript在初始化之前无法访问类