使用 Laravel Eloquent 从数据库中获取两个日期之差等于一个值的记录

存在一个users带有列的表hire_date。目标是计算hire_date查询中用户日期和当前日期之间的年差。


我想获取hire_dateas|1989-10-07 02:06:44|和 now 之间的差异在数组中的记录 as[6,9,30]


目前我已经尝试过这个


<?php


namespace 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". 我怎样才能解决这个问题?


斯蒂芬大帝
浏览 160回答 1
1回答

哆啦的时光机

尝试使用 CarbonsubYears()获取日期,并与 比较hire_date,我们可以使用它date_format来将时间戳转换为日期:$dates_ago = collect([15, 30, 35, 40])->map(function($num) {&nbsp; &nbsp; 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();
打开App,查看更多内容
随时随地看视频慕课网APP