Emile Caron
Emile Caron

Reputation: 29

Laravel: use value of another column within a function in Where statement

I have a Round model for a game in Laravel PHP. Each round has a start time (DATETIME) and a duration (INT) in minutes:

id | game_id  | duration | start_time
1  | 3        | 40       | 2022-06-22 19:29:26
2  | 3        | 20       | 2022-06-24 00:02:55
3  | 1        | 10       | 2022-06-25 10:56:05

a game will have multiple rounds, a round has ended if start_time + duration > Carbon::now()

Now what I can't seem to figure out is how to retrieve all rounds from a game that are still ongoing

I thought something like this but obviously this doesn't work because I can't put the "duration" column in the subMinutes function

return $game->whereHas('rounds', function ($query) {
            $query->where('start_time', '>', Carbon::now()->subMinutes(duration));
        })->first();

Upvotes: 1

Views: 1329

Answers (1)

pmcpimentel
pmcpimentel

Reputation: 691

You're looking for this in SQL:

WHERE start_time > CURRENT_TIMESTAMP - INTERVAL duration SECOND

or the same, in Eloquent:

$query->whereRaw(sql: 'WHERE start_time > CURRENT_TIMESTAMP - INTERVAL duration SECOND');

Upvotes: 1

Related Questions