laravel eloquent query group by last id

前端 未结 3 383
执念已碎
执念已碎 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();
    
    0 讨论(0)
  • 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 . '<br>');
        }
    }
    
    0 讨论(0)
  • 2021-01-20 06:38
    public function latest($equipamentos)
        {
            foreach ($equipamentos as $equip) 
            {
                $latest[$equip->cod] = DB::table('tb_calibracao')
                                    ->where('cod_equipamento', $equip->cod)
                                    ->where('parecer', '1')
                                    ->orderBy('cod', 'Desc')
                                    ->first();
            }
    
            return $latest; 
        }
    

    That worked, thx for the help!

    0 讨论(0)
提交回复
热议问题