如何解析date_birth字段为仅月日格式以查询员工生日?
解决Laravel中按生日(月日)查询员工的问题
你当前的代码无法正确查询,因为date_birth字段是Y-m-d的日期类型,直接和m-d格式的字符串对比会匹配失败。以下是几种可行的解决方案:
方法一:使用数据库原生函数(以MySQL为例)
通过DATE_FORMAT函数提取date_birth的月日部分,再与当前日期的月日做对比,同时用参数绑定避免SQL注入:
$getBirthday = Karyawan::whereRaw('DATE_FORMAT(date_birth, "%m-%d") = ?', [Carbon::now()->format('m-d')])->get();
方法二:使用Laravel查询构建器的日期方法
用whereMonth和whereDay分别匹配月份和日期,这种写法更符合Laravel风格,且兼容多种数据库:
$today = Carbon::now(); $getBirthday = Karyawan::whereMonth('date_birth', $today->month) ->whereDay('date_birth', $today->day) ->get();
方法三:处理闰年2月29日的特殊情况
如果需要兼容闰年出生的员工(非闰年时匹配2月28日),可以添加额外判断:
$today = Carbon::now(); $query = Karyawan::query(); if ($today->month == 2 && $today->day == 28 && !$today->isLeapYear()) { // 非闰年2月28日,同时匹配2月28和2月29的生日 $query->where(function ($q) { $q->whereMonth('date_birth', 2)->whereDay('date_birth', 28) ->orWhereMonth('date_birth', 2)->whereDay('date_birth', 29); }); } else { $query->whereMonth('date_birth', $today->month) ->whereDay('date_birth', $today->day); } $getBirthday = $query->get();
内容的提问来源于stack exchange,提问作者slvhxia
相关产品推荐
相关产品推荐

