Posted on: July 26, 2021 09:41 AM
Posted by: Renato
Views: 2434
Laravel - Obtenha registros entre duas datas usando MySQL Interval
O whereBetween
método Laravel Query Builder fornece um método muito fácil de usar para consultar registros entre duas datas.
Você pode simplesmente escrever um código como este:
$startDate = Carbon::createFromFormat('d/m/Y', '09/10/2020')->format('Y-m-d'); $endDate = Carbon::now()->format('Y-m-d'); Visit::whereBetween
('date', [$startDate
,$endDate
])->get();
Mas o que acontece se você quiser usar o MySQL Interval Operator
Por exemplo, consultas de visitas em que a data foi entre 2 anos atrás e 1 ano mais um mês atrás
$startDate = " CURDATE() - INTERVAL 2 YEAR"; $endDate = " CURDATE() - INTERVAL 1_1 YEAR_MONTH" ; Visit::whereBetween('date', [$startDate, $endDate])->get();
Dá a seguinte consulta errada :
select * from `visits` where `date` between 'CURDATE() - INTERVAL 2 YEAR' and ' CURDATE() - INTERVAL 1_1 YEAR_MONTH'
Para usar o MySQL, Interval Operator
você precisa usar o whereRaw
método.
$startDate = " CURDATE() - INTERVAL 2 YEAR"; $endDate = " CURDATE() - INTERVAL '1_1' YEAR_MONTH" ; Visit::whereRaw('date BETWEEN '.$startDate.' and '.$endDate)->get();
Isso produz a seguinte consulta:
select * from `visits`
where date BETWEEN CURDATE() - INTERVAL 2 YEAR and CURDATE() - INTERVAL '1_1' YEAR_MONTH
Função de intervalo
A tabela abaixo descreve a unidade associada à expressão da função de intervalo.
unit | Expression |
DAY | DAYS |
DAY_HOUR | ‘DAYS HOURS’ |
DAY_MICROSECOND | ‘DAYS HOURS:MINUTES:SECONDS.MICROSECONDS’ |
DAY_MINUTE | ‘DAYS HOURS:MINUTES’ |
DAY_SECOND | ‘DAYS HOURS:MINUTES:SECONDS’ |
HOUR | HOURS |
HOUR_MICROSECOND | ‘HOURS:MINUTES:SECONDS.MICROSECONDS’ |
HOUR_MINUTE | ‘HOURS:MINUTES’ |
HOUR_SECOND | ‘HOURS:MINUTES:SECONDS’ |
MICROSECOND | MICROSECONDS |
MINUTE | MINUTES |
MINUTE_MICROSECOND | ‘MINUTES:SECONDS.MICROSECONDS’ |
MINUTE_SECOND | ‘MINUTES:SECONDS’ |
MONTH | MONTHS |
QUARTER | QUARTERS |
SECOND | SECONDS |
SECOND_MICROSECOND | ‘SECONDS.MICROSECONDS’ |
WEEK | WEEKS |
YEAR | YEARS |
YEAR_MONTH | ‘YEARS-MONTHS’ |
$from = date('2018-01-01');
$to = date('2018-05-02');
Reservation::whereBetween('reservation_from', [$from, $to])->get();
****
Reservation::all()->filter(function($item) {
if (Carbon::now->between($item->from, $item->to) {
return $item;
}
});
****
Reservation::whereBetween('reservation_from', [$from1, $to1])
->orWhereBetween('reservation_to', [$from2, $to2])
->whereNotBetween('reservation_to', [$from3, $to3])
->get();
****
$fromDate = "2016-10-01";
$toDate = "2016-10-31";
$reservations = Reservation::whereRaw(
"(reservation_from >= ? AND reservation_from <= ?)",
[$fromDate." 00:00:00", $toDate." 23:59:59"]
)->get();
- https://www.youtube.com/watch?v=FjHvM_wDf3I
#laravel #eloquent #mysql
Donate to Site
Renato
Developer