get row count according to the month in the date in Laravel

久未见 提交于 2019-12-25 03:27:26

问题


I want a query in laravel to group by data with dateofSale's month with the count of rows with the same month.

here is my table

and I want to output something like this

numberOfSales | Month
     2           Nov
     1           Oct

how can I do it?


回答1:


You should be able to achieve this what you're after with:

$data = \App\SaleData::selectRaw('COUNT(*) as count, YEAR(dateOfSale) year, MONTH(dateofSale) month')
    ->groupBy('year', 'month')
    ->get();

If you don't include the year as well then you'll have sales from different years included in the same month e.g. sales from October 2017 and October 2018 will be included together.




回答2:


you can try as

$data = SalesData::select(DB::raw('count('*') as `count`'), DB::raw('MONTH(dateOfSale) month'))
         ->groupBy(function($m) {
             return Carbon::parse($m->dateOfSale)->format('m');
         })->get();

don't forget to import carbon and DB on top of your controller like

use DB;
use Carbon\Carbon;


来源:https://stackoverflow.com/questions/53461005/get-row-count-according-to-the-month-in-the-date-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!