简体   繁体   中英

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.

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.

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?

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()

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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