Поиск между датами без учета года
К примеру, диапазон от $from = 30.06.2022 по $to = 02.08.2022, нужно выбрать всех пользователей у которых в этом периоде есть день рождения.
User::query()->whereBetween('birthday', [$from, $to])->get(['id', 'name']);
Данный запрос найдет пользователей строго с учетом 2022 года. Как сделать так, чтобы выборка была именно по датам месяцев?
Ответы (1 шт):
Автор решения: vottiv
→ Ссылка
Нашел следующее решение:
$startMonth = $value['from']->format('m');
$endMonth = $value['to']->format('m');
if ($startMonth === $endMonth) {
$query->whereMonth($field, $startMonth)
->whereDay($field, '>=', $value['from']->format('d'))
->whereDay($field, '<=', $value['to']->format('d'));
} else {
$query->where(function ($query) use ($value, $field) {
$query->whereMonth($field, $value['from']->format('m'))
->whereDay($field, '>=', $value['from']->format('d'))
->whereDay($field, '<=', $value['from']->copy()->endOfMonth()->format('d'));
})
->orWhere(function ($query) use ($value, $field) {
$query->whereMonth($field, $value['to']->format('m'))
->whereDay($field, '>=', $value['to']->copy()->startOfMonth()->format('d'))
->whereDay($field, '<=', $value['to']->format('d'));
});
$months = [];
// месяца между выбранными датами
while ($startMonth + 1 < $endMonth) {
$startMonth++;
$months[] = $startMonth;
}
if (!empty($months)) {
foreach ($months as $month) {
$query->orWhereMonth($field, $month);
}
}
}