Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get latest values in GROUP BY using Laravel Eloquent ORM

Tags:

php

orm

laravel

I'm trying to understand how Laravel's Eloquent ORM works and was looking at the following MySQL query:

SELECT id, name, date FROM tablename GROUP BY name ORDER BY date

The use of GROUP BY always returns the oldest values of name. Is there a way to return the latest value instead?

like image 940
enchance Avatar asked May 10 '13 07:05

enchance


Video Answer


1 Answers

Try following code,

Tablename::select('id', 'name', DB::raw('max(date) as latest_date'))
 ->groupBy('name')
 ->orderBy('latest_date')
 ->get()
like image 178
sulaiman sudirman Avatar answered Oct 12 '22 03:10

sulaiman sudirman