Laravel Eloquent: Select Rows with Maximum Created_at
In Laravel Eloquent, you may encounter scenarios where you need to select all rows with the maximum created_at value for each unique seller_id in a table. Here's how you can achieve this:
Using Raw SQL Query
One approach is to use a raw SQL query, which could be more efficient for certain circumstances:
<code class="sql">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
Alternatively, you can utilize Laravel's query builder for a more object-oriented approach:
<code class="php"> 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();</code>
Both methods will return a collection of objects representing the latest rows for each unique seller_id in the snapshot table.
The above is the detailed content of How to Select Rows with the Maximum `created_at` for Each Unique `seller_id` in Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!