存在一個(gè)users帶有列的表hire_date。目標(biāo)是計(jì)算hire_date查詢中用戶日期和當(dāng)前日期之間的年差。我想獲取hire_dateas|1989-10-07 02:06:44|和 now 之間的差異在數(shù)組中的記錄 as[6,9,30]目前我已經(jīng)嘗試過這個(gè)<?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(); }}但它返回錯(cuò)誤:message: "DateTime::__construct(): Failed to parse time string (hire_date) at position 0 (h): The timezone could not be found in the database". 我怎樣才能解決這個(gè)問題?
1 回答

哆啦的時(shí)光機(jī)
TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
嘗試使用 CarbonsubYears()獲取日期,并與 比較hire_date,我們可以使用它date_format來將時(shí)間戳轉(zhuǎn)換為日期:
$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 關(guān)注
- 178 瀏覽
添加回答
舉報(bào)
0/150
提交
取消