Search code examples
laraveleloquentsql-timestamp

how to add minutes to milliseconds in laravel query, and apply where condition?


I have a table named activities, where waiting_time is in minutes and start_time is in milliseconds.

Name   | event_start_waiting_time | event_time |
running| 30                       |1685944961000  |
walking| 20                       | 1686481069000 |

for eg. event_time is 5:00 PM and event_start_waiting_time is 30 minutes i.e.. I can start activity anytime between 5:00 PM - 5:30 PM. I want to fetch those activities according to my current time. if current time lies between any of the activity range, fetch that activity.

$currentTimestamp = time() * 1000; 
$activities = Activity::where('event_start_waiting_time', '<=', $currentTimestamp)
    ->whereRaw('(event_time + (event_start_waiting_time * 60 * 1000)) >= ?', [$currentTimestamp])
    ->get();

I have tried this query, but getting the empty result.


Solution

  • Here is an example,

    $minutes = 5; // The number of minutes to add
    $milliseconds = $minutes * 60 * 1000; // Convert minutes to milliseconds
    
    $results = DB::table('your_table')
        ->whereRaw('your_column + ? <= UNIX_TIMESTAMP()', [$milliseconds])
        ->get();