php - 拉维尔 : How to take last n(any number) rows after ordered in ascending order?

标签 php mysql sorting laravel laravel-4

  1. 我的模型表中有 3 列 idmsgcreated_atcreated_at 是时间戳,id 是主键。
  2. 我还有 5 个数据,world => time4hello => time2haha => time1hihio = > time5dunno => time3 并且这些数据根据它们的 id 按升序排列(如此处排列)。

在 laravel 4 中,我想获取这些数据,将它们按升序排列并取最后 n(在本例中为 3)条记录。所以,我想在 div 中像这样显示 dunnoworldhihio 行:

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/

相关文章:

php - 如何使用 PHP 和 MySQL 数据库制作预订 ID?

php - 在 X-Editable 中通过 Ajax 提交数据

php - mysql连接问题

mysql - 错误 1064 (42000) MySQL。 (没有缩进,一切都用反引号转义

php - 在 mysql 中,一行总是在最上面

algorithm - 合并排序与其他数据结构?

PHP 与 Oledb

php - Inner Join WITH 和 inner join ON 有什么区别?

javascript - 如何在不同页面上发表不同意见

php - 在保留键的同时使用排序