2

I have a table that contains:

id  seller_id   amount   created_at
1   10          100      2017-06-01 00:00:00
2   15          250      2017-06-01 00:00:00
....
154 10          10000    2017-12-24 00:00:00
255 15          25000    2017-12-24 00:00:00

I want to get all the latest rows for each individual seller_id. I can get the latest row for one like this:

$sales = Snapshot::where('seller_id', '=', 15)
    ->orderBy('created_at', 'DESC')
    ->first();

How do I get only the latest row for each seller?

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
TheRealPapa
  • 4,393
  • 8
  • 71
  • 155

3 Answers3

4

To get latest record for each seller_id you can use following query

select s.*
from snapshot s
left join snapshot s1 on s.seller_id = s1.seller_id
and s.created_at < s1.created_at
where s1.seller_id is null

Using query builder you might rewrite it as

DB::table('snapshot as s')
  ->select('s.*')
  ->leftJoin('snapshot as s1', function ($join) {
        $join->on('s.seller_id', '=', 's1.seller_id')
             ->whereRaw(DB::raw('s.created_at < s1.created_at'));
   })
  ->whereNull('s1.seller_id')
  ->get();
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
1

This worked:

DB::table('snapshot as s')
  ->select('s.*')
  ->leftJoin('snapshot as s1', function ($join) {
        $join->on('s.seller_id', '=', 's1.seller_id');
        $join->on('s.created_at', '<', 's1.created_at');
   })
  ->whereNull('s1.seller_id')
  ->get();
TheRealPapa
  • 4,393
  • 8
  • 71
  • 155
0

Following the answer in https://stackoverflow.com/a/31624248/6779467, in Laravel 10, you can use self::from instead of DB::table to have the same results but with full models instead of just arrays.

in Snapshot model (Snapshot.php)

use Illuminate\Database\Eloquent\Builder;

//...

public function scopeLatestForEachSeller(Builder $query): Builder
{
    /**
     * In case the table name is modified by code elsewhere,
     * we use the table name retrieval method.
     */
    $table = $this->getTable();

    return self::from($table . ' as s')
        ->select('s.*')
        ->leftJoin($table . ' as s1', function ($join) {
            $join->on('s.seller_id', '=', 's1.seller_id')
                ->on('s.created_at', '<', 's1.created_at');
        })
        ->whereNull('s1.seller_id');
}

anywhere else in the code

$snapshots = Snapshot::latestForEachSeller()->get();