Laravel 4 and Eloquent ORM - How to select the last 5 rows of a table

China☆狼群 提交于 2019-12-22 08:39:25

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/23300062/laravel-4-and-eloquent-orm-how-to-select-the-last-5-rows-of-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!