Home >Database >Mysql Tutorial >How to Get the Most Recent Row for Each Seller ID Using Laravel Eloquent?
You have a table that contains data with seller_id and created_at columns. You want to retrieve only the latest rows for each distinct seller_id.
Using Laravel Eloquent's query builder, you can achieve this by employing a left join and a whereNull condition. Here's how:
$subquery = DB::table('snapshot') ->where('seller_id', '=', 's1.seller_id') ->whereRaw('s.created_at < s1.created_at'); $query = DB::table('snapshot as s') ->select('s.*') ->leftJoinSub($subquery, 's1', function ($join) { $join->on('s.seller_id', '=', 's1.seller_id'); }) ->whereNull('s1.seller_id') ->get();
In this query:
By executing this query, you will obtain a collection of the latest rows for each distinct seller_id in the snapshot table.
The above is the detailed content of How to Get the Most Recent Row for Each Seller ID Using Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!