存在一个users带有列的表hire_date。目标是计算hire_date查询中用户日期和当前日期之间的年差。我想获取hire_dateas|1989-10-07 02:06:44|和 now 之间的差异在数组中的记录 as[6,9,30]目前我已经尝试过这个<?phpnamespace App\Http\Controllers\API;use App\Http\Controllers\Controller;use Illuminate\Http\Request;use App\ServiceAwardYear;use App\User;use Carbon\Carbon;class LongServiceAwardController extends Controller{ public function index() { $records = [9,6]; foreach($records as $record){ $employees = User::where(Carbon::parse('hire_date')->diffInYears(Carbon::now()), $record)->get(); }}但它返回错误:message: "DateTime::__construct(): Failed to parse time string (hire_date) at position 0 (h): The timezone could not be found in the database". 我怎样才能解决这个问题?
1 回答
哆啦的时光机
TA贡献1779条经验 获得超6个赞
尝试使用 CarbonsubYears()获取日期,并与 比较hire_date,我们可以使用它date_format来将时间戳转换为日期:
$dates_ago = collect([15, 30, 35, 40])->map(function($num) {
return Carbon::now()->subYears($num)->format('Y-m-d');
})->all();
User::whereIn(\DB::raw("date_format(hire_date, '%Y-%m-%d')"), $dates_ago)->get();
或者只是使用TIMESTAMPDIFF()
User::whereIn(\DB::raw("TIMESTAMPDIFF(YEAR, hire_date, NOW())"), [15, 30, 35, 40])->get();
- 1 回答
- 0 关注
- 150 浏览
添加回答
举报
0/150
提交
取消