"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Select Rows with the Maximum `created_at` for Each Unique `seller_id` in Laravel Eloquent?

How to Select Rows with the Maximum `created_at` for Each Unique `seller_id` in Laravel Eloquent?

Published on 2024-11-06
Browse:945

How to Select Rows with the Maximum `created_at` for Each Unique `seller_id` in Laravel Eloquent?

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.

Latest tutorial More>

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