简体   繁体   中英

Laravel groupBy and raw queries

I have never really worked with groupBy or raw queries, especially for a long time. I am just wondering if the following is possible:

$payments = Payment::all();

$grouped = $payments->groupBy('date');

dd($grouped->toArray());

The above will give me the following output:

"2018-08-21" => array:1 [▶]
"2018-06-21" => array:1 [▶]

What I want to do, is grab the data like this:

"2018-08-21" => array:2 [▶]

So basically I want to turn the months into the current month, and then group the data by the day. In the above example, the date 21-06-2018 has changed to 21-08-2018 and it was grouped with the other date on the 21st.

So to simply put, I just want to group the results by the day of my date column, whilst ignoring the months and years. Is this possible with a (raw) query, or should I manipulate the data afterwards?

This worked for me:

$payments = Payment::orderBy('created_at', 'DESC')->get()
        ->groupBy(function($date) {
            return Carbon::parse($date->date)->format('d');
        });

You could also have used something similar to what @elitepc answered, the reason your solution works is because you are using correctly the groupBy Collection function, this solution uses the groupBy Eloquent query builder function. Not to get confused with them, or you gonna have a bad time.

This should work:

$payments = Payment::orderBy('created_at', 'DESC')
    ->groupBy(DB::raw('DAY(date)'))
    ->get();

Yes it is possible. You can try this.

$payments = Payment::->select(*, DB::raw('DAY(date) AS day'))->get();

$grouped = $payments->groupBy('day');

dd($grouped->toArray());

You can do a group by like this if I remember correctly:

$grouped = $payments->groupBy(DB::raw('DAY(date)'));

That way only the day part of the date will be considered to be grouped.

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