'Eloquent ORM and relative where time statement
I'm using ORM Eloquent and I need to filter all models using a date interval and an own property of the model.
The raw SQL would be:
SELECT * FROM model WHERE start >= NOW() - INTERVAL duration MINUTES
Where start
is a datetime
and duration
is an int of model table.
Is it possible to write a where statement? Is there an alternative to write a RAW query?
Event::where('start', '>=', ? )->get();
The start
field is indexed.
Solution 1:[1]
Best way to go about this is to calculate the interval on the application side.
E.g.: checking for a 30 minutes interval:
$minutesPast = (new DateTime('-30 minutes'))->format('d/m/Y h:i:s');
Event::where('start', '>=', $minutesPast )->get();
I rather calculate times and dates on the application side anyway, since that way there's a single source of truth, and I don't have to worry about the DB server maybe not being on the same timezone as the application server, etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | yivi |