2015-10-27 21 views
13

私はレポートページを作成しています。私がしたいのは、特定の日付から特定の日付までのレポートを表示することです。現在のコードはLaravel Eloquent Date Range - 2つの日付間のクエリ

$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' 'での日付フォーマットが何でありますか。それに基づいてCarbon値を使用することができます。 –

+0

の日付形式はTIMESTAMP @AthiKrishnan – FewFlyBy

+2

です。Reservation :: where( 'reservation_from'、 '> ='、Carbon :: createFromDate(1975、5、21);) - >ここで、 '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

を同じようにあなたのクエリ:

これが助けた 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(); 
関連する問題