"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 Fetch the Latest Snapshot for Each Seller Using Laravel Eloquent?

How to Fetch the Latest Snapshot for Each Seller Using Laravel Eloquent?

Published on 2024-11-09
Browse:592

How to Fetch the Latest Snapshot for Each Seller Using Laravel Eloquent?

Eloquent Query for Selecting Latest Rows Grouped by Seller

Given a table consisting of seller-related information including created_at timestamps, it's often necessary to retrieve only the most recent entries for each seller. This task can be accomplished effectively using Laravel Eloquent.

To achieve this, we can employ a MySQL subquery that identifies the latest row for each seller_id using a left join and NULL matching. This subquery can then be used in conjunction with Eloquent to retrieve the desired data.

In SQL, the query would look like this:

select s.*
from snapshot s
left join snapshot s1 on s.seller_id = s1.seller_id
and s.created_at 

Translated into Laravel Eloquent, the query would be written as follows:

DB::table('snapshot as s')
  ->select('s.*')
  ->leftJoin('snapshot as s1', function ($join) {
        $join->on('s.seller_id', '=', 's1.seller_id')
             ->whereRaw(DB::raw('s.created_at whereNull('s1.seller_id')
  ->get();

This query retrieves the latest snapshot row for each unique seller_id using the subquery, ensuring that the returned results represent the most up-to-date information for each seller.

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