gpt4 book ai didi

php - Laravel 5.4 : Eloquent. 查找最近的日期

转载 作者:行者123 更新时间:2023-11-29 02:13:33 25 4
gpt4 key购买 nike

我有一组用户,其中包含出生日期。我如何使用 Eloquent ORM 获得最接近的生日,而无需将 native 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'), []);
}

Dates in DB

提前致谢。

最佳答案

我已经通过以下方式解决了问题:

   /**
* 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']), []);
}

像魅力一样工作。

关于php - Laravel 5.4 : Eloquent. 查找最近的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45060598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com