简体   繁体   中英

laravel, How to check if this is the last record

how can I check if the current record is the last one in the model?

   $lastorder=Order::find($order_id);
    if($lastorder->last())

You could do it all in one round trip to the database!

In MySQL you'd write:

SELECT *
FROM oders
WHERE id = (SELECT MAX(id) FROM orders) AND id = [$order_id]

So in Eloquent you'd write something like:

Order::where('id', $order_id)
     ->where('id', function($q) {
         $query->selectRaw('MAX(id)')
               ->from('orders');
     })->first();

Check if that is null and you'll know!

$orders = Order::where('id','>=', $order_id)->get();

$order = $orders->first();

if($orders->count() > 1) {
   //...
   // NOT the last record :(
   //...
} else { 
   //...
   // Last record :)
   //...
}
$order=Order::find($order_id);
$last_record = Order::orderBy('id', 'desc')->first();
if($order->id == $last_record->id)
{
    //last record;
}

Assuming that Order table contains id as primary key.

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