2017-03-08 114 views
0

我需要從DB結果按日期,例如今天,昨天,本週,上週劃分等充分利用數據庫特定的日期範圍在Laravel

我可以很容易地whereRaw和一些SQL這樣做:

whereRaw('Date(created_at) = CURDATE()')->get(); 

我不知道是否有一個更容易,適當的方式來做到這一點與雄辯。

+0

您的原始SQL不按範圍過濾。 –

+0

@AlexBlex這僅僅是一個如何得到今天的例子,很顯然,當我想要擴大範圍時,我會擴展它。 – prgrm

+0

如果http://stackoverflow.com/questions/24824624/laravel-q-where-between-dates,http://stackoverflow.com/questions/33361628/laravel-eloquent-date-range,等不給你提示,請參閱文檔https://laravel.com/docs/5.4/queries#where-clauses? –

回答

1

你可以爲這樣一個特定的類創建範圍:

public function scopeYourQuery($query, $user) { 
    return $query->where('user_id', $user->id)->orderBy('created_at', 'desc')->first(); 
} 

這只是得到由每個用戶created_at日期排序,下行的有序列表的第一項。

如果你想要日期範圍之間的東西?你只需通過在你的日期,並延長了一點與一些PHP,也許像這樣的工作:

public function scopeSomeDateQuery($query, $fetch_date, $user) 
{ 
    //clone the users chosen month - so we can make the range until the following month 
    $also_fetch_date = clone $fetch_date; 
    $next_month = $also_fetch_date->addMonth(); 
    $next_month = $next_month->format('Y-m-d'); 
    $fetch_date = $fetch_date->format('Y-m-d'); 
    //return the query for the monthname 
    return $query->orderBy('created_date')->where('created_date', '>=', $fetch_date)->where('created_date', '<', $next_month)->where('user_id', $user->id); 
} 

這看在每月的範圍(每用戶)來獲取項目的有序列表與CREATED_DATE在那個範圍內。

+0

我在問是否有一個現成的雄辯的方式要實現這一目標,但由於看起來並不是一個好的開始。謝謝。 – prgrm

+0

是的,不是我所知道的 - 我認爲你必須用自己的意見自己製作查詢。如果你找到更好的方法 - 讓我知道!我經常遇到類似的疑問! – Hanny