我已阅读过Laravel文档,但我无法完成这项工作。
有人知道在Eloquent中是否可以进行此查询吗?
如果是这样,你会怎么写呢?
SELECT
MONTHNAME(postdate) as monthname,
DATE_FORMAT(postdate,'%m') as month,
YEAR(postdate) as year,
COUNT(MONTHNAME(postdate)) as num
FROM
postData
WHERE
status = 1
GROUP BY
monthname,
year
ORDER BY
postdate DESC
答案 0 :(得分:3)
虽然简单地使用DB::raw
进行整个查询确实有效,但对我来说感觉不对。您可能希望使用查询生成器尝试此解决方案。
DB::table('postData')->select([
DB::raw('MONTHNAME(postdate) AS monthname'),
DB::raw('DATE_FORMAT(postdate, \'%m\') AS month'),
DB::raw('YEAR(postdate) AS year'),
DB::raw('COUNT(MONTHNAME(postdate)) AS num'),
])->where('status', 1)
->groupBy('monthname', 'year')
->orderBy('postdate', 'DESC');
它仍然使用DB::raw
,但仅适用于select子句。无论如何,您可以使用PostData
模型而不是DB::table('postData')
,但由于它实际上不是常规PostData
对象,我建议不要使用它。
答案 1 :(得分:2)
如果您不介意使用DB :: raw(),请执行此操作...
轻松复制......
DB :: select(DB :: raw(" SELECT MONTHNAME(postdate)作为monthname,DATE_FORMAT(postdate,'%m')作为月份, 年(postdate)为年,COUNT(MONTHNAME(postdate))为num FROM postData WHERE status = 1 GROUP BY monthname,year ORDER BY postdate DESC"));
一行......
DB::select(DB::raw("SELECT MONTHNAME(postdate) as monthname, DATE_FORMAT(postdate,'%m') as month,YEAR(postdate) as year, COUNT(MONTHNAME(postdate)) as num FROM postData WHERE status = 1 GROUP BYmonthname,year ORDER BY postdate DESC"));