Reputation: 2866
I'm trying to find records by time interval. In table there are columns like 'date_from' and 'date_to', those are specify starts and ends date of an event.
public function scopeByTimeInterval($query, $dateInterval)
{
$query->where(function ($query) use ($dateInterval) {
[$from, $to] = $dateInterval;
$query->where([
['date_from', '<=', $from],
['date_to', '>=', $to]
]);
$query->orWhere([
['date_from', '>=', $from],
['date_to', '<=', $to]
]);
$query->orWhereBetween('date_from', $dateInterval);
$query->orWhereBetween('date_to', $dateInterval);
});
}
when I use where
query directly, there are no problem. I can see all events between those dates. But if I use it as a scope, it returns me every events in given year and month and not the interval..
What might cause kind of behavior ? Or am I missing something ?
Upvotes: 0
Views: 373
Reputation: 35170
As mentioned in the comments, your query is essentially selecting everything. If you're trying to get the events that are happening during the $from
and $to
dates you could do something like:
public function scopeDateInterval($query, $interval)
{
[$from, $to] = $interval;
$query
->where(function ($query) use ($from, $to) {
$query
->where(function ($query) use ($from) {
$query
->where('date_from', '<=', $from)
->where('date_to', '>=', $from);
})
->orWhere(function ($query) use ($to) {
$query
->where('date_from', '<=', $to)
->where('date_to', '>=', $to);
})
->orWhere(function ($query) use ($from, $to) {
$query
->where('date_from', '>=', $from)
->where('date_to', '<=', $to);
});
});
}
The above is basically saying where the $from
or $to
is between the start and end dates, or the start and end dates are between the $from
and $to
.
Upvotes: 2