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

存在一个包含列的表。目标是计算查询中用户日期与当前日期之间的年差。usershire_datehire_date


我想获取 as 和 now 之间的差异在数组中的记录,如hire_date|1989-10-07 02:06:44|[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".我该如何解决这个问题?


临摹微笑
浏览 145回答 1
1回答

神不在的星期二

尝试使用 Carbon's 来获取日期,并与 进行比较,我们可以使用它将时间戳转换为日期:subYears()hire_datedate_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