Home  >  Article  >  Backend Development  >  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?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 12:15:30285browse

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:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn