【问题标题】:Laravel : How to take last n(any number) rows after ordered in ascending order?Laravel:如何在按升序排序后取最后 n(任意数量)行?
【发布时间】:2014-07-31 23:54:29
【问题描述】:
  1. 我的模型表中有 3 列 idmsgcreated_atcreated_at 是时间戳,id 是主键。
  2. 我还有 5 个数据,world => time4hello => time2haha => time1hihio => time5dunno => time3,这些数据根据它们的id 升序排列(如此处排列)。李>

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

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() 更好的解决方案加分。非常感谢!

【问题讨论】:

  • 使用orderBy('created_at', 'desc')->take(3),然后反转数组。

标签: php mysql sorting laravel laravel-4


【解决方案1】:

您的第二次尝试已经很接近了。从数据库中检索行后,您只需要反转数组。假设您有一个Illuminate\Support\Collection 的实例,您只需要执行以下操作:

$expectedResult = $collection->reverse();

【讨论】:

    【解决方案2】:

    你们很亲密。

    听起来你想先按降序排列数组

      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 站点http://laravel.com/api/class-Illuminate.Support.Collection.html 上查看 Laravel 的 Collection 文档

    现在 $dates 将包含您想要的输出。

    dunno,time3
    world,time4
    hihio,time5
    

    【讨论】:

      【解决方案3】:
      $reverse = Model::orderBy('created_at','desc')->take(3);
      
      $show = $reverse->reverse();
      

      【讨论】:

        【解决方案4】:

        按升序获取最后三行:

        $_dates = Model::orderBy('created_at','desc')->take(3)->reverse();
        

        现在,$_dates 的 json 输出将为您提供一个对象对象。

        要获取对象数组,请使用:

        $_dates = Model::orderBy('created_at','desc')->take(3)->reverse()->values();
        

        【讨论】:

          猜你喜欢
          • 2023-03-09
          • 2021-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-26
          • 2021-12-11
          • 2010-12-02
          相关资源
          最近更新 更多