2014-06-11 26 views
8
  1. 我在我的模型表中有3列id,msgcreated_atcreated_at是時間戳,id是主鍵。
  2. 我也有基於其id 5個DATAS,world => time4hello => time2haha => time1hihio => time5dunno => time3和這些的數據都是按升序排列(如下安排)。

在laravel 4中,我想要獲取這些數據,按升序排列它們並取最後n個(本例中爲3)個記錄。所以,我想在一個div像這樣顯示dunnoworldhihio行:Laravel:如何按升序排列後的最後n個(任意數量)行?

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()更好的解決方案的積分。非常感謝你!

+2

使用'orderBy('created_at','desc') - > take(3)',然後顛倒數組。 –

回答

7

你非常接近。

這聽起來像你想的降序排列

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

第一順序排列,但隨後扭轉陣列。你可以通過兩種方法之一來完成這一點,無論是傳統的PHP(使用array_reverse)。

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

還是laravel方式,使用Laravel的Collectionreverse功能。

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

退房Laravel的Collection在他們的API站點http://laravel.com/api/class-Illuminate.Support.Collection.html

現在$文件日期將包含你想要的輸出。

dunno,time3 
world,time4 
hihio,time5 
3

你與你的第二次嘗試非常接近。從數據庫中檢索行之後,您只需要反轉數組。假設你有Illuminate\Support\Collection一個實例,你只需要如下:

$expectedResult = $collection->reverse(); 
相關問題