سؤال

I'm trying to figure out how to select the last 5 rows of a table to display on a home screen when there might be gaps in the ids. The database this is for has 1,000s of rows and I don't want to have to call all of them to take the last 5 every time I go to my app's home screen. The problem is that rows sometimes are deleted in the database for various reasons so, for example, if the last row's id is 4023 the second to last row's id might be 4020, so I can't just use the length and count backwards. Ideally it would work like

$get_5_rows = DB::table('rows')->take(5)->get();

Except that instead of collecting the first 5 rows that it would take the last 5.

Thank y'all so much for the help! Any and all help is greatly appreciated!

هل كانت مفيدة؟

المحلول

You may try this:

$rows = DB::table('rows')->orderBy('id', 'desc')->take(5)->get();

You may also use orderBy('created_at') if that field is available. Another similar answer here.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top