2015-10-27 47 views
13

我正在創建一個報告頁面,我想要做的是顯示從特定日期到特定日期的報告。我目前的代碼是:Laravel雄辯的日期範圍 - 兩個日期之間的查詢

$now = date('Y-m-d'); 
$reservations = Reservation::where('reservation_from', $now)->get(); 

這是幹什麼的,是select * from table where reservation_from = $now。我在這裏有一個查詢,但我不知道如何將其轉換爲雄辯的查詢。這是我的代碼:

SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to 

如何將代碼轉換爲雄辯的查詢?先謝謝你。

+0

是什麼'reservation_from'日期格式。您可以使用基於此的碳值。 –

+0

日期格式是TIMESTAMP @AthiKrishnan – FewFlyBy

+2

它就像'Reservation :: where('reservation_from','> =',Carbon :: createFromDate(1975,5,21);) - > where('reservation_from', '<=',Carbon :: createFromDate(2015,5,21);) - > get()'; –

回答

29

whereBetween方法驗證列的值是 兩個值之間。

嘗試:

$reservations = Reservation::whereBetween('reservation_from', [$from, $to])->get(); 

如果你想添加更多的條件,就可以使用orWhereBetween

$reservations = Reservation::whereBetween('reservation_from', [$from_from, $to_from]) 
       ->orWhereBetween('reservation_to', [$from_to, $to_to]) 
       ->get(); 

你應該知道:whereNotBetweenwhereInwhereNotInwhereNullwhereNotNull

Laravel docs about where.

2

以下應該工作:

$now = date('Y-m-d'); 
$reservations = Reservation::where('reservation_from', '>=', $now) 
          ->where('reservation_from', '<=', $to) 
          ->get(); 
4

試試這個:

因爲你是基於單個列值取得被可以簡化您的查詢同樣如下:

$reservations = Reservation::whereBetween('reservation_from', array($from, $to))->get(); 

根據條件檢索:laravel docs

希望這對我有所幫助。

2

另一種選擇,如果你的領域是datetime而不是date然而它可以用於兩種情況):

$fromDate = "2016-10-01"; 
$toDate = "2016-10-31"; 

$reservations = Reservation::whereRaw("reservation_from >= ? AND reservation_from <= ?", 
    array($fromDate." 00:00:00", $toDate." 23:59:59") 
)->get(); 
相關問題