Laravel:如何以升序排序后的最后n(任意数量)行? [英] Laravel : How to take last n(any number) rows after ordered in ascending order?

查看:139
本文介绍了Laravel:如何以升序排序后的最后n(任意数量)行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我的模型表中有3列idmsgcreated_at. created_at是时间戳,id是主键.
  2. 我还有5个数据,分别为world => time4hello => time2haha => time1hihio => time5dunno => time3,这些数据基于它们的id以升序排列(如下所示).
  3. li>
  1. I have 3 columns id, msg and created_at in my Model table. created_at is a timestamp and id is primary key.
  2. I also have 5 datas, world => time4, hello => time2,haha => time1,hihio => time5 and dunno => time3 and these datas are arranged in ascending order (as arranged here) based on their id.

在laravel 4中,我想获取这些数据,将它们按升序排列,并获取最后n个记录(在这种情况下为3个)记录.因此,我想在div中像这样显示dunnoworldhihio行:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆