Laravel:如何以升序排序后的最后n(任意数量)行? [英] Laravel : How to take last n(any number) rows after ordered in ascending order?
问题描述
- 我的模型表中有3列
id
,msg
和created_at
.created_at
是时间戳,id
是主键. - 我还有5个数据,分别为
world => time4
,hello => time2
,haha => time1
,hihio => time5
和dunno => time3
,这些数据基于它们的id
以升序排列(如下所示). li>
- I have 3 columns
id
,msg
andcreated_at
in my Model table.created_at
is a timestamp andid
is primary key. - I also have 5 datas,
world => time4
,hello => time2
,haha => time1
,hihio => time5
anddunno => time3
and these datas are arranged in ascending order (as arranged here) based on theirid
.
在laravel 4中,我想获取这些数据,将它们按升序排列,并获取最后n个记录(在这种情况下为3个)记录.因此,我想在div中像这样显示dunno
,world
和hihio
行:
In laravel 4, I want to fetch these data, arrange them in ascending order and take the last n(in this case, 3) number of records. So, I want to get dunno
,world
and hihio
rows displayed like this in a div :
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()
给予更好的解决方案加分.非常感谢你!
This problem seems fairly simple but I just can't seem to get my logic right. I'm still fairly new in Laravel 4 so I would give bonus points to better solutions than using orderBy()
and take()
if there is. Thank you very much!
推荐答案
您非常亲密.
听起来您想先按降序对数组进行排序
It sounds like you want to first order the array by descending order
Model::orderBy('created_at','desc')->take(3);
,然后反转数组.您可以通过两种方式之一执行此操作,或者是传统的PHP(使用array_reverse).
but then reverse the array. You can do this one of two ways, either the traditional PHP (using array_reverse).
$_dates = Model::orderBy('created_at','desc')->take(3);
$dates = array_reverse($_dates);
或者使用laravel方法,使用Laravel Collection
类中的reverse
函数.
Or the laravel way, using the reverse
function in Laravel's Collection
class.
$_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
在其API网站 http://上查看Laravel的Collection
文档. laravel.com/api/class-Illuminate.Support.Collection.html
Check out Laravel's Collection
documentation at their API site at http://laravel.com/api/class-Illuminate.Support.Collection.html
现在$ dates将包含您想要的输出.
Now $dates will contain the output you desire.
dunno,time3
world,time4
hihio,time5
这篇关于Laravel:如何以升序排序后的最后n(任意数量)行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!