简体   繁体   English

Laravel 4和Eloquent ORM - 如何选择表格的最后5行

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

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. 我试图找出如何选择表格的最后5行,以便在ID中可能存在间隙时显示在主屏幕上。 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. 这个数据库有1000行,我不想每次去我的应用程序主屏幕时都要调用所有这些行来获取最后5行。 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. 问题是由于各种原因有时会在数据库中删除行,因此,例如,如果最后一行的id是4023,则倒数第二行的id可能是4020,所以我不能只使用长度并向后计数。 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. 除了收集前5行,而不是收集最后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. 如果该字段可用,您也可以使用orderBy('created_at') Another similar answer here . 另一个类似的答案在这

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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