laravel eloquent query group by last id

前端 未结 3 405
执念已碎
执念已碎 2021-01-20 06:09

Hi I\'m trying to get the last register in DB for each equipment

I got like

id   | id_equip
-----+----------
   1 |    3
   2 |    3
   3 |    3
            


        
3条回答
  •  深忆病人
    2021-01-20 06:29

    I'm not sure if there's an easier way and this is kind of convoluted because of the join, but it should give the result you want:

    DB::table('equip as e')
        ->select('e.*')
        ->join(DB::raw("(SELECT id_equip, MAX(id) id FROM equip GROUP BY id_equip) as _e"), function ($join) {
            $join->on('e.id', '=', '_e.id')->on('e.id_equip', '=', '_e.id_equip');
        })
        ->orderBy('id', 'asc')
        ->get();
    

提交回复
热议问题