簡體   English   中英

如何分頁對象數組laravel?

[英]how to paginate object array laravel?

當我嘗試對登錄用戶傳遞的結果進行分頁時,出現錯誤:

$message = Auth::user()->Notifications()->orderBy('created_at', 'desc')->get()
        ->groupBy(function($date) {
            return Carbon::parse($date->created_at)->format('M d'); // grouping by day
        })
        ->paginate(2);

調用未定義的方法Illuminate \\ Database \\ Eloquent \\ Collection :: paginate()

有什么問題,如何對對象數組進行分頁?

嘗試這個:

$message = Auth::user()->Notifications()->orderBy('created_at', 'desc')
    ->groupBy(function($date) {
        return Carbon::parse($date->created_at)->format('M d'); // grouping by day
    })->paginate(2);

paginate方法必須是鏈中的最后一個元素,例如-> get()

//編輯:如此處所述: http : //laravel.com/docs/4.2/pagination

注意:目前,使用Laravel無法有效執行使用groupBy語句的分頁操作。 如果需要使用帶有分頁結果集的groupBy,建議您手動查詢數據庫並使用Paginator :: make。

這也可能會有所幫助: http : //www.jenssegers.be/blog/57/laravel-pagination-with-grouping-and-eager-loading

當然,當groupBy返回Illuminate\\Support\\Collection的實例時,您會收到錯誤groupBy 您需要做類似的事情

$messages = Auth::user()->Notifications()->orderBy('created_at', 'desc')->paginate(2);

$messages->setItems($messages->groupBy(function($date) {
            return $date->created_at->format('M d'); // grouping by day
        }));

這樣,您可以在分頁對象中設置新項目,這些新項目是數據庫中的分組結果。

暫無
暫無

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

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