Selecting All Rows with Maximum created_at Value for Each seller_id in Laravel Eloquent
Your table contains a list of sales transactions with columns including id, seller_id, amount, and created_at. To retrieve the most recent row for each unique seller_id, you can employ the following techniques:
Using a SQL Query
To directly execute a custom SQL query, you can use the DB facade in Laravel:
$latestSales = DB::select(DB::raw(' 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 Eloquent Query Builder
Alternatively, you can utilize Laravel's query builder to achieve the same result:
$latestSales = DB::table('snapshot as s') ->select('s.*') ->leftJoin('snapshot as s1', function ($join) { $join->on('s.seller_id', '=', 's1.seller_id') ->whereRaw('s.created_at < s1.created_at'); }) ->whereNull('s1.seller_id') ->get();
Both techniques will fetch all the rows with maximum created_at values for all unique seller_id values in your table.
The above is the detailed content of How to Select the Latest Sale for Each Seller in Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!