我有一張表,其中包含學生的所有資料。我只需要少于一年中選定月份的月份資料。我有這樣的日期列資料。
registrationdate
2022-01-31
2021-12-01
2022-07-01
2021-11-12
2021-10-10
2022-01-07
2020-08-26
如果我選擇第 12 個月和 2021 年,我只需要 2021 年 12 月的先前資料
$月=12 和 $年=2021
$selectedmonthMalestudents = \DB::table('students')
->whereRaw('extract(month from registrationdate) = ?','<' [$month])
->whereRaw('extract(year from registrationdate) = ?', [$year])
->count();
請幫助我如何做這些......
uj5u.com熱心網友回復:
只需呼叫eloquent的whereMonthandwhereYear方法即可。我懷疑這是否可以與 DB::table 一起使用,但無論如何您都可以使用該模型。
$selectedmonthMalestudents = \DB::table('students')
->whereMonth('salary_date', $month)
->whereYear('salary_date', $year)
->count();
個人建議:-始終使用模型而不是 DB::table();
uj5u.com熱心網友回復:
首先,你不應該在 laravel 中使用 Raw SQL 陳述句,除非在某些情況下因為安全問題而絕對必要
所以在你的控制器中,你可以使用Carbon
public function index(Students $student) {
$date = Carbon::parse(' Decemeber of 2021 ');
$result = $student->where('registrationdate', '<', $date)->get();
return response()->json([compact('result'), 200]);
}
或使用 Laravel 的 Eloquent ORM Map 收集方法,如
public function index(Students $student) {
$date = Carbon::parse(' Decemeber of 2021 ');
$result = $student->filter(function($std, $key) {
$created_at = Carbon::now($std['registration_date']);
if($create_at->isBefore($date)) {
return true;
}
})->get();
return response()->json([compact('result'), 200]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406396.html
標籤:
下一篇:SQLSTATE[42S02]:未找到基表或視圖:1146表“mkstudent.classes_student”不存在(SQL:插入“classes_student”(“classes_id”,
