dongtang1944 2016-08-01 20:32
浏览 27
已采纳

两个日期之间的碳返回生日

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);
        }
  • 写回答

1条回答 默认 最新

  • doqp87012 2016-08-01 20:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)
  • ¥100 使用matlab解决含分段变量的优化问题
  • ¥15 matlab基于鲸鱼算法优化vmd
  • ¥20 PCB设计与制作问答
  • ¥20 课堂跑如何下载ppt
  • ¥15 STM32阿里云平台显示不了传感器采集的数据
  • ¥20 三菱FX系列PLC上位机串口下指令置位M64和M65,这两条指令分别是什么呢?
  • ¥15 有关结冰模拟程序咨询