Laravel 5.4:Eloquent。查找最近的日期
Laravel 5.4 : Eloquent. Find closest dates
我有一组用户,其中包含出生日期。
我如何使用 Eloquent ORM 获得最接近的生日而不将本机 SQL 查询推入其中?
我也试过下一段代码,但不能正常工作:
/**
* Returns 10 closest birthdays
*
* @return \Illuminate\Http\JsonResponse
*/
public function birthdays()
{
$carbon = new Carbon();
$date = "%-" .
$carbon->month < 10 ? "0{$carbon->month}" : $carbon->month . "-" .
$carbon->day < 10 ? "0{$carbon->day}" : $carbon->day . "-";
$birthdays = User::latest('dob')
->whereRaw("dob > {$date}")
->limit(10)
->get();
return $this->jsonResponse(compact('birthdays'), []);
}
提前致谢。
我已经通过以下方式解决了问题:
/**
* Returns 10 closest birthdays
*
* @return \Illuminate\Http\JsonResponse
*/
public function birthdays()
{
$date = date('m-d');
$today_birthdays = User::whereRaw("dob like '%-$date'")
->orderBy('dob', 'desc')
->get();
$upcoming_birthdays = User::whereRaw('DAYOFYEAR(curdate()) + 1 <= DAYOFYEAR(dob) and dob not like \'%-' . $date . '\'')
->orderBy('dob', 'desc')
->limit(10)
->get();
return $this->jsonResponse(compact(['upcoming_birthdays', 'today_birthdays']), []);
}
很有魅力。
我有一组用户,其中包含出生日期。 我如何使用 Eloquent ORM 获得最接近的生日而不将本机 SQL 查询推入其中?
我也试过下一段代码,但不能正常工作:
/**
* Returns 10 closest birthdays
*
* @return \Illuminate\Http\JsonResponse
*/
public function birthdays()
{
$carbon = new Carbon();
$date = "%-" .
$carbon->month < 10 ? "0{$carbon->month}" : $carbon->month . "-" .
$carbon->day < 10 ? "0{$carbon->day}" : $carbon->day . "-";
$birthdays = User::latest('dob')
->whereRaw("dob > {$date}")
->limit(10)
->get();
return $this->jsonResponse(compact('birthdays'), []);
}
提前致谢。
我已经通过以下方式解决了问题:
/**
* Returns 10 closest birthdays
*
* @return \Illuminate\Http\JsonResponse
*/
public function birthdays()
{
$date = date('m-d');
$today_birthdays = User::whereRaw("dob like '%-$date'")
->orderBy('dob', 'desc')
->get();
$upcoming_birthdays = User::whereRaw('DAYOFYEAR(curdate()) + 1 <= DAYOFYEAR(dob) and dob not like \'%-' . $date . '\'')
->orderBy('dob', 'desc')
->limit(10)
->get();
return $this->jsonResponse(compact(['upcoming_birthdays', 'today_birthdays']), []);
}
很有魅力。