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:
select s.*
from snapshot s
left join snapshot s1 on s.seller_id = s1.seller_id
and s.created_at Using Query Builder
Alternatively, you can utilize Laravel's query builder for a more object-oriented approach:
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 whereNull('s1.seller_id')
->get();
Both methods will return a collection of objects representing the latest rows for each unique seller_id in the snapshot table.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3