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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊