1
Hello, I’m having problems using Laravel’s eloquent to create an SQL that meets the following demand: "return a query if there is a reservation made in a certain period of time"; Following the code of my function which, checks whether a reservation has already been made for that particular period
private function isOut($timeIn, $timeOut)
{
$timeIn = date_format(date_create($timeIn), 'Y-m-d H:i:s');
$timeOut = date_format(date_create($timeOut), 'Y-m-d H:i:s');
$output = new Output();
$query = $output->select('*')
->where('users_id', Auth::user()->id)
->where(function($q) use ($timeIn,$timeOut){
$q->orWhere(function($s) use ($timeIn,$timeOut){
$s->whereDate('start_at','>=',$timeIn)
->whereDate('start_at','<=',$timeOut);
})->orWhere(function ($s) use ($timeIn, $timeOut){
$s->whereDate('end_at','>=',$timeIn)
->whereDate('end_at','<=',$timeOut);
});
})
->get()
->toArray();
return $query;
}
As stated above, its purpose is to check whether in the time interval of start_at and end_at there is any reservation made. As a basis, for this code I created the following SQL:
select * from `outputs`
where `users_id` = 1
AND (
(
`start_at` >= CONVERT('2019-03-09 13:00:00',DATETIME)
AND `start_at` <= CONVERT('2019-03-10 13:00:00',DATETIME)
)
OR
(
`end_at` >= CONVERT('2019-03-09 13:00:00',DATETIME)
AND `end_at` <= CONVERT('2019-03-10 13:00:00',DATETIME)
)
)
and `outputs`.`deleted_at` is NULL
However, this is the code I picked up on the debbuger relating to what I wrote above:
select * from `outputs`
where `users_id` = 1
AND (
(
DATE (`start_at`) >= '2019-03-09 13:00:00'
AND DATE(`start_at`) <= '2019-03-10 13:00:00'
)
OR
(
DATE(`end_at`) >= '2019-03-09 13:00:00'
AND DATE(`end_at`) <= '2019-03-10 13:00:00'
)
)
and `outputs`.`deleted_at` is null
So my doubt, to work with dates, I found no other way if not the use of ->whereDate() in Laravel, but this function can not meet the demand, because I believe it is only looking at the DATE format of the string, being necessary to consider DATETIME, in summary: There is some other way to use DATETIME in Laravel, or there is something I missed concerning the comparison of dates by the framework?
Does it have to be within two dates? wouldn’t it
between
, example:$data between start_at and end_at
?– novic
I can’t believe it worked, Oia was so much looking for a way to ensure that mysql would read the string as DATETIME that I didn’t even try the basics, really thank you
– Leonardo da Silva
Put as answer the solution found ... !
– novic