存在一個包含列的表。目標是計算查詢中用戶日期與當前日期之間的年差。usershire_datehire_date我想獲取 as 和 now 之間的差異在數組中的記錄,如hire_date|1989-10-07 02:06:44|[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貢獻1963條經驗 獲得超6個贊
嘗試使用 Carbon's 來獲取日期,并與 進行比較,我們可以使用它將時間戳轉換為日期:subYears()hire_datedate_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 關注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消