Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-25 12:15:30
Original
376 people have browsed it

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
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template