Detta är det enklaste och kortaste sättet att få groupBy Max Date i laravel. Ta raderna med maxdatum med group by user_id
.
$rows = DB::table('papers')
->select(DB::raw('id, max(paper_update) as year,user_id'))
->groupBy('user_id')
//->orderBy('paper_update', 'desc')
->get();
Denna laravel-fråga kommer att skapa en mysql-fråga som denna
select id, max(paper_update) as year from `papers` group by `user_id`;
Utgången blir
Array
(
[0] => stdClass Object
(
[id] => 4
[year] => 30-5-2013
[user_id] => 1
)
[1] => stdClass Object
(
[id] => 5
[year] => 30-5-2013
[user_id] => 2
)
[2] => stdClass Object
(
[id] => 6
[year] => 30-5-2014
[user_id] => 3
)
[3] => stdClass Object
(
[id] => 7
[year] => 30-5-2014
[user_id] => 4
)
[4] => stdClass Object
(
[id] => 10
[year] => 30-5-2016
[user_id] => 5
)
)