简体   繁体   中英

Carbon return birthday between two dates

I have this method to return all users with a birthday between two dates, I am doing the following query (using laravel):

public function birthdays()
{
    return Contact::whereBetween(DB::raw('DATE_FORMAT(birthday, "%m-%d")'), array(
        $this->startDate->format('m-d'),
        $this->endDate->format('m-d')))
        ->get();
}

It is working flawlessly. However, when I am searching between let's say December and January, it doesn't work, since the query returns null, obviously, because it's searching without the year. In my database I just store the birthday as their full birthday, for example: 1985-01-10.

How can I get it to work to also be able to search between december->january or november->may?

Edit: I cannot add the year in the query, since it wouldn't return all birthdays. Or am I missing something?

public function upcomingMonths($months = '2')
{
    $this->startDate = Carbon::now();
    $this->endDate = Carbon::now()->addMonth(''.$months.'');

    return $this;
}

I am using the class for more than just returning birthdays, for example, also appointments, and other stuff since I chain the methods:

$calendar = new App\Calendar;

$appointments = $calendar->upcomingMonths()->appointments();
$birthdays = $calendar->upcomingMonths()->birthdays();

Edit: Got it working like this:

        if($this->month($this->endDate) < $this->month($this->startDate))
        {
            $a = Contact::whereBetween(DB::raw('DATE_FORMAT(birthday, "%m-%d")'), array(
                $this->startDate->format('m-d'),
                '12-31'))
                ->get();

            $b = Contact::whereBetween(DB::raw('DATE_FORMAT(birthday, "%m-%d")'), array(
                '01-01',
                $this->endDate->format('m-d')))
                ->get();

            $result = $a->merge($b);

            dd($result);
        }

If you can't add the year and the problem is at the end of the year, you could detect if the end date has changed of year (end date month < start date month) and then split the query in 2: one from de start date until the end of the year and the other from the beginning of the year until the end date. Then you have to merge both collections and return it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM