简体   繁体   English

Laravel 查询生成器按天计算行数 SQL db::raw

[英]Laravel query builder count rows by day SQL db::raw

I've got a Laravel 8 application whereby I need to count the number of total applications for each day and output a count of the data in the most efficient way, for instance, 500 applications on 1st, 1,000 applications on 2nd and so fourth, depending on how many applications there are each day.我有一个 Laravel 8 应用程序,我需要计算每天的总应用程序数量,output 以最有效的方式计算数据,例如,1 日有 500 个应用程序,2 日有 1,000 个应用程序,以此类推,取决于每天有多少应用程序。

I'm using DB::raw() to count my rows, however, Laravel's timestamps by default includes the hours, minutes and seconds as part of the date, and so this isn't going to work for me, I need to format the date to exclude this and just contain the day.我正在使用DB::raw()来计算我的行数,但是,Laravel 的时间戳默认包括小时、分钟和秒作为日期的一部分,所以这对我不起作用,我需要格式化排除此日期并仅包含日期的日期。

My query doesn't seem to be returning anything, and no error either, so I think there's something wrong with my first DB::raw() , it doesn't seem to be formatted the created_at column at all, what am I missing?我的查询似乎没有返回任何内容,也没有错误,所以我认为我的第一个DB::raw()有问题,它似乎根本没有格式化created_at列,我错过了什么?

Application::whereBetween('created_at', [$from, $to])
           ->select(DB::raw('DATE_FORMAT("created_at, %Y-%m-%d")'), DB::raw('count(*) as applications'))
           ->groupBy('created_at')
           ->get();

You can use groupByRaw()您可以使用 groupByRaw()

Application::whereBetween('created_at', [$from, $to])
           ->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'), DB::raw('count(*) as applications'))
           ->groupByRaw('DATE_FORMAT(created_at, "%Y-%m-%d")')
           ->get();

Also, you can use selectRaw() instead of select(DB::raw)此外,您可以使用 selectRaw() 而不是 select(DB::raw)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM