Home > Database > Mysql Tutorial > How to Select the Latest Sale for Each Seller in Laravel Eloquent?

How to Select the Latest Sale for Each Seller in Laravel Eloquent?

Susan Sarandon
Release: 2024-11-30 06:02:13
Original
974 people have browsed it

How to Select the Latest Sale for Each Seller in Laravel Eloquent?

Selecting All Rows with Maximum created_at Value for Each seller_id in Laravel Eloquent

Your table contains a list of sales transactions with columns including id, seller_id, amount, and created_at. To retrieve the most recent row for each unique seller_id, you can employ the following techniques:

Using a SQL Query

To directly execute a custom SQL query, you can use the DB facade in Laravel:

$latestSales = DB::select(DB::raw('
    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 Eloquent Query Builder

Alternatively, you can utilize Laravel's query builder to achieve the same result:

$latestSales = 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();
Copy after login

Both techniques will fetch all the rows with maximum created_at values for all unique seller_id values in your table.

The above is the detailed content of How to Select the Latest Sale for Each Seller 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