A
A
Alexander Frolov2019-10-23 17:31:18
Laravel
Alexander Frolov, 2019-10-23 17:31:18

How to make a request grouped by date?

Comrades, fellow citizens, help me write a request correctly. The bottom line is this: there are operations with the creation date (created_at) and the amount (payment_sum). You need to make a request to withdraw the amount for all transactions by day.
In the database, the date is stored like this:
2019-10-23 10:41:41
In the controller, I have this:

$date = Carbon\Carbon::today()->subDays(7);

$todaySales = (Operation::query()
        ->select(DB::raw("created_at, SUM(payment_sum) as payment_sum"))
        ->where([
            ['user_id', Auth::id()],
            ['status', 100]])
        ->where('created_at','>',  $date)
        ->groupBy('columnForGroup')
        ->get());

        foreach ($todaySales as $todaySale){
            $date = $todaySale->created_at;
            $todaySale->date_at = $date->format('d/m');
        }

        return response()->json([
            'success' => true,
            'mass' => $todaySales,
        ]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Enj0y, 2019-10-23
@14frol14

It is obvious to use a function in grouping
->groupBy("DATE_FORMAT(created_at, '%d-%m-%Y')")

A
Alexander Frolov, 2019-10-24
@14frol14

Thanks for the answer. Decided already. If someone is interested, then did so.

->select(DB::raw("DATE(created_at) as day, count(payment_sum) as payment_sum"))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question