簡體   English   中英

檢索最近 3 年的所有行(Laravel + Eloquent)

[英]Retrieve all rows from the last possible 3 years (Laravel + Eloquent)

我試圖在模型中獲取所有行,但它必須是最近 3 年,好像我在 2020 年有結果但在 2019 年沒有任何結果,那么它必須在 2018 年、2017 年進行搜索,但如果我在 2019 年有結果,那么它必須只搜索 2018 年的結果。

我已經掌握了 whereBetween,但是我沒有使用以下查詢從數據庫中獲得任何結果:

$year = $request->all();
$fromDate = $year['yearFrom'];
$toDate = $year['yearTo'];

return Tipico::whereBetween(
    DB::raw('date(created_at)'), [$fromDate, $toDate]
)
    ->get();

如您所見,我從 post 方法中獲取年份,該方法為我提供了初始和完成年份,但是它並沒有驗證我正在搜索的信息,最好的方法是什么?

使用 Carbon 創建日期:

$fromDate = Carbon::createFromDate($year['yearFrom'], 1, 1)->startOfDay();
$toDate = Carbon::createFromDate($year['yearTo'], 12, 31)->endOfDay();

然后在您的查詢中, created_at已經是一個日期時間,所以:

return Tipico::whereBetween('created_at', [$fromDate, $toDate])->get();

請記住將 Carbon 包含在您的班級頂部:

use Illuminate\Support\Carbon;

或僅

use Carbon\Carbon;

要獲取過去 3 年的數據,一種選擇是運行查詢以查看哪些年份擁有您需要的數據。

所以,讓我們使用yearTo作為他的參考並選擇前 3 年的數據:

$years = Tipico::select(\DB::raw('YEAR(created_at) as years'))
               ->where('created_at', '<=', $toDate)
               ->distinct()
               ->orderByRaw('YEAR(created_at) DESC')
               ->limit(3)
               ->get();

現在以$years您將擁有 3 年。 現在您可以使用此年份作為參數運行查詢:

return Tipico::whereIn(\DB::raw('YEAR(created_at)'), $years)->get();

*不確定是否可以直接傳遞$years或需要轉換為數組。 看一看。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM