简体   繁体   中英

laravel count records based on each single date

In my database I have records something like

**my_table_name**

id      date_column               status
1       2020-07-21 00:29:05       done
2       2020-07-21 21:29:05       done
3       2020-07-21 21:35:05       failed
4       2020-07-22 10:29:05       done
5       2020-07-22 10:35:05       done
6       2020-07-22 10:37:05       failed
7       2020-07-22 10:39:05       failed
8       2020-07-22 10:40:05       done

And using laravel query I want result like

array(
    [0]=>array(
        'date'=>'2020-07-21',
        'failed'=>1
        'done'=>2
     ),
   [0]=>array(
        'date'=>'2020-07-22',
        'failed'=>2
        'done'=>3
     )
)

How can I do this?

I have tried

$record=DB::table('my_table_name')
                    ->select(
                            DB::raw("DATE_FORMAT(date_column, 'Y-m-d') as date"),
                            DB::raw("SUM(status= 'failed') as failed"),
                            DB::raw("SUM(status= 'done') as done"),
                            )
                    ->where('date_column','>=','2020-07-21 00:00:00')
                    ->where('date_column','<=','2020-07-22 23:59:59')
                    ->groupBy(DB::raw("DATE_FORMAT(date_column, 'Y-m-d')"))
                    ->get();

Thanks in advance

Your code seems to be fine but using date format of 'Ymd' instead of '%Y-%m-%d' which is wrong.

In order to solve your issue, use below query:

DB::table('my_table_name')::select(
            DB::raw("DATE_FORMAT(date_column, '%Y-%m-%d') as date"),
            DB::raw("SUM(name= 'failed') as failed"),
            DB::raw("SUM(name= 'done') as done"),
            )
            ->whereDate('date_column','>=','2020-07-21')
            ->whereDate('date_column','<=','2020-07-22')
            ->groupBy(DB::raw("DATE_FORMAT(date_column, '%Y-%m-%d')"))
            ->get();

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