Laravel : How to take last n(any number) rows after ordered in ascending order?

天大地大妈咪最大 提交于 2019-12-23 07:39:07

问题


  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.

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

What I have tried

Model::orderBy('created_at','asc')->take(3);

undesired result :

haha,time1
hello,time2
dunno,time3

Also tried

Model::orderBy('created_at','desc')->take(3);

undesired result :

hihio,time5
world,time4
dunno,time3

I have also tried the reverse with no luck

Model::take(3)->orderBy('created_at','asc');

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!


回答1:


You are very close.

It sounds like you want to first order the array by descending order

  Model::orderBy('created_at','desc')->take(3);

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);

Or the laravel way, using the reverse function in Laravel's Collection class.

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

Check out Laravel's Collection documentation at their API site at http://laravel.com/api/class-Illuminate.Support.Collection.html

Now $dates will contain the output you desire.

dunno,time3
world,time4
hihio,time5



回答2:


You're pretty close with your second attempt. After retrieving the rows from the database, you just need to reverse the array. Assuming you have an instance of Illuminate\Support\Collection, you just need to the following:

$expectedResult = $collection->reverse();



回答3:


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

$show = $reverse->reverse();



来源:https://stackoverflow.com/questions/24154208/laravel-how-to-take-last-nany-number-rows-after-ordered-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!