laravel eloquent query group by last id

前端 未结 3 384
执念已碎
执念已碎 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:33

    A simple way, without join, using max:

    $query = DB::table('equip')
        ->select(DB::raw('*, max(id) as id'))
        ->groupBy('id_equip')
        ->orderBy('id', 'asc')
        ->get();
    

    (Assuming, of course, that you can count on your id to be in date order.)


    You can also do this with Eloquent, using a self-referencing one-to-one relationship. The query takes longer, but it's much more Laravel-like:

    Define the relationship in your model:

    class myModel extends Eloquent {
        public function latestEquipment()
        {
            return $this->hasOne('myModel', 'id_equip', 'id_equip')->latest();
        }
    }
    

    (Note that in this case, we're using latest() so that we don't rely on the order of ids to determine the most recent entry, but rather on the created_at date of each record. This is more accurate.)

    To retrieve all the records, with their latest equipment entry:

    $latest = myModel::with('latestEquipment')->groupBy('id_equip')->get();
    // loop over the results
    foreach ($latest as $l) {
        if ($l->equipment) {
            echo('ID: ' . $l->id . 'ID_EQUIP: ' . $l->id->id_equip . '
    '); } }

提交回复
热议问题