Laravel - Get the last entry of each UID type

后端 未结 6 2007
栀梦
栀梦 2020-11-30 15:46

I have a table that has 100\'s of entries for over 1000 different products, each identified by a unique UID.

ID  UID                 MANY COLUMNS    CREATED          


        
6条回答
  •  感情败类
    2020-11-30 16:37

    You can use a self join to pick latest row for each UID

    select t.*
    from yourTable t
    left join yourTable t1 on t.uid = t1.uid
    and t.created_at < t1.created_at 
    where t1.uid is null
    

    Using laravel's query builder it would be similar to

    DB::table('yourTable as t')
        ->select('t.*')
        ->leftJoin('yourTable as t1', function ($join) {
            $join->on('t.uid','=','t1.uid')
                 ->where('t.created_at', '<', 't1.created_at');
        })
        ->whereNull('t1.uid')
        ->get();
    

    Laravel Eloquent select all rows with max created_at

    Laravel Eloquent group by most recent record

提交回复
热议问题