[英]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): 我有此方法返回两个日期之间有生日的所有用户,我正在执行以下查询(使用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.
在我的数据库中,我只是将生日存储为他们的完整生日,例如:1985-01-10。
How can I get it to work to also be able to search between december->january or november->may? 我怎样才能在12月-> 1月或11月->可能之间搜索呢?
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. 如果您无法添加年份并且问题出在年底,则可以检测结束日期是否已更改年份(结束日期月份<开始日期月份),然后将查询分为2:开始日期,直到年末,另一个开始日期,直到年末。 Then you have to merge both collections and return it.
然后,您必须合并两个集合并返回它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.