- 我的模型表中有 3 列
id
、msg
和created_at
。created_at
是时间戳,id
是主键。 - 我还有 5 个数据,
world => time4
,hello => time2
,haha => time1
,hihio = > time5
和dunno => time3
并且这些数据根据它们的id
按升序排列(如此处排列)。
在 laravel 4 中,我想获取这些数据,将它们按升序排列并取最后 n(在本例中为 3)条记录。所以,我想在 div 中像这样显示 dunno
、world
和 hihio
行:
dunno,time3
world,time4
hihio,time5
我尝试过的
Model::orderBy('created_at','asc')->take(3);
不希望的结果:
haha,time1
hello,time2
dunno,time3
也试过
Model::orderBy('created_at','desc')->take(3);
不希望的结果:
hihio,time5
world,time4
dunno,time3
我也试过相反的方法,但没有成功
Model::take(3)->orderBy('created_at','asc');
这个问题看起来很简单,但我似乎无法正确理解我的逻辑。我在 Laravel 4 中还是相当新的,所以如果有的话,我会给比使用 orderBy()
和 take()
更好的解决方案加分。非常感谢!
最佳答案
你们很亲近。
听起来你想先对数组进行降序排序
Model::orderBy('created_at','desc')->take(3);
然后反转数组。您可以通过两种方式之一执行此操作,传统的 PHP(使用 array_reverse)。
$_dates = Model::orderBy('created_at','desc')->take(3);
$dates = array_reverse($_dates);
或者使用 Laravel 的方式,使用 Laravel 的 Collection
类中的 reverse
函数。
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
在他们的 API 站点查看 Laravel 的 Collection
文档 http://laravel.com/api/class-Illuminate.Support.Collection.html
现在 $dates 将包含您想要的输出。
dunno,time3
world,time4
hihio,time5
关于php - 拉维尔 : How to take last n(any number) rows after ordered in ascending order?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24154208/