Swaz

Group by 2 columns and show latest for each group

Posted 1 year ago by Swaz

I'm trying to group by 2 columns and show the latest entry for each group, but can't get it working. Does anyone know how to do this?

Products Table

id | type_id | category_id | price | created_at

Current Data

1 | 5 | 10 | 25.00 | 2017-01-01
2 | 5 | 10 | 50.00 | 2017-01-03
3 | 8 | 10 | 75.00 | 2017-01-05

Expected Output

2 | 5 | 10 | 50.00 | 2017-01-03
3 | 8 | 10 | 75.00 | 2017-01-05

Actual Output

1 | 5 | 10 | 25.00 | 2017-01-01
3 | 8 | 10 | 75.00 | 2017-01-05

Here's what I'm currently trying

Product::select(DB::raw('*, max(created_at) as date'))
    ->orderBy('date')
    ->groupBy('type_id')
    ->groupBy('category_id')
    ->get();

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.