2015-10-27 21 views
13

Sto creando una pagina di report e quello che volevo fare è mostrare i report da una data specifica a una data specifica. Il mio codice attuale è:Intervallo di date eloquente di Laravel - Richiesta tra due date

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

Quello che fa è a select * from table where reservation_from = $now. Ho una query qui ma non so come convertirla in query eloquenti. Questo è il mio codice:

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

Come posso convertire il codice in query eloquente? Grazie in anticipo.

+0

Qual è il formato della data in 'reservation_from'. puoi usare i valori di Carbon basati su questo. Il formato data –

+0

è TIMESTAMP @AthiKrishnan – FewFlyBy

+2

sarebbe come, 'Reservation :: where ('reservation_from', '> =', Carbon :: createFromDate (1975, 5, 21);) -> dove ('reservation_from', '<=', Carbon :: createFromDate (2015, 5, 21);) -> get() '; –

risposta

29

Procedimento whereBetween verifica che il valore di una colonna è tra due valori.

Prova:

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

Se si desidera aggiungere ulteriori condizioni, è possibile utilizzare orWhereBetween.

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

Si dovrebbe conoscere: whereNotBetween, whereIn, whereNotIn, whereNull, whereNotNull

Laravel docs about where.

2

Il seguente dovrebbe funzionare:

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

Prova questa:

Dal momento che state cercando di caricare sulla base di un singolo valore di colonna è possibile semplificare la vostra domanda allo stesso modo:

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

recuperare sulla base condizione: laravel docs

Spero che questo ha aiutato.

2

Un'altra opzione se il campo è datetime invece di date (anche se funziona per entrambi i casi):

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