简体   繁体   中英

Laravel fetch latest record based on created_at datetime field

In my E-Commerce web application, I am trying to implement International Shipping Feature. The relationship is like:

One international shipping zone hasMany Countries and a Country belongsTo a shippig zone.

One international shipping zone hasMany Shipping rate applied and one Shipping Rate belongsTo one Shipping Zone.

Now what I want to trying to do is to fetch the all the shipping rates that are created in descending order. Uptil now, I can fetch it correctly without any issue. Now here comes the twist . If there is one shipping rate having the same shipping rate code in the table, fetch the latest record and ignore the previous record, based on the country that will be selected by the user on the front end.

The code that I have tried:

$shippingCountryId = session()->get('new_shipping_country');
$shippingCountryAmount = session()->get('new_shipping_amount');

if ($shippingCountryId !== null) {
    $shippingAll = ShippingCountry::find($shippingCountryId)
                                    ->zone->rates()
                                    ->latest()->get();
} else {
    $shippingAll = ShippingCountry::where('name', 'India')->first()
                                    ->zone->rates()
                                    ->latest()->get();
}

The above code fetches all the records from the rates table for that shipping zone when the user selects the shipping country, which I don't want. I want only the latest one to be fetched if there is more than one record found with the same code.

Collection methods didn't work for me:

unique() , contains() , search() , filter()

I know I am pretty sure that I must be making some silly mistake, but I cannot find out what mistake and where.

Kindly help me out with this. I am trying to solve this since 2 days, but could not succeed yet.

Any help is highly appreciated. Thank you in advance.

Well latest method is just for ordering. If you want to fetch just the one - latest record you have to change get (you'll get an ordered collection here) to first :

$shippingCountryId = session()->get('new_shipping_country');
$shippingCountryAmount = session()->get('new_shipping_amount');

if ($shippingCountryId !== null) {
    $latestRate = ShippingCountry::find($shippingCountryId)
                                    ->zone->rates()
                                    ->latest()->first();
} else {
    $latestRate = ShippingCountry::where('name', 'India')->first()
                                    ->zone->rates()
                                    ->latest()->first();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM