sql >> Base de Datos >  >> RDS >> Mysql

Laravel 4 Query Builder - groupBy Fecha máxima

Esta es la forma más fácil y corta de obtener groupBy Max Date en laravel. Tome las filas con fecha máxima con grupo por 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();

Esta consulta laravel creará una consulta mysql como esta

select id, max(paper_update) as year from `papers` group by `user_id`;

La salida será

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
        )
)