0

К примеру, диапазон от $from = 30.06.2022 по $to = 02.08.2022, нужно выбрать всех пользователей у которых в этом периоде есть день рождения.

User::query()->whereBetween('birthday', [$from, $to])->get(['id', 'name']);

Данный запрос найдет пользователей строго с учетом 2022 года. Как сделать так, чтобы выборка была именно по датам месяцев?

1 ответ 1

0

Нашел следующее решение:

    
    
    $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);
            }
        }
    }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.