6

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?

4

2 回答 2

7

试试下面的代码,

Tablename::select('id', 'name', DB::raw('max(date) as latest_date'))
 ->groupBy('name')
 ->orderBy('latest_date')
 ->get()
于 2015-05-05T07:35:42.667 回答
0

Here's a working SQL query that only gets the latest results that are unique for what you choose with a.id = b.id - if you wanted to do unique names, then it'd be a.name = b.name.

SELECT DISTINCT a.*
FROM tablename a
LEFT JOIN tablename b ON a.id = b.id
AND a.date < b.date
WHERE b.date IS NULL
于 2013-11-11T23:30:57.340 回答