2017-07-06 106 views
0

我想使用雄辯讓我按照響應分組,並同時給我一個分頁響應(讓我鏈接到第二頁)。 我試圖做到這一點:在使用GroupBy和分頁時獲取錯誤Eloquent

App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) { 
    return Carbon\Carbon::parse($row->created_at)->format('Y-m-d'); 
})->paginate(25); 

但是,我得到的補鍋匠運行時,它這個錯誤:

PHP warning: strtolower() expects parameter 1 to be string, object given in D:\Folder\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58 

沒有GROUPBY,我得到正確的結果:

>>> App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->paginate(25)->toArray(); 
=> [ 
    "total" => 1, 
    "per_page" => 25, 
    "current_page" => 1, 
    "last_page" => 1, 
    "next_page_url" => null, 
    "prev_page_url" => null, 
    "from" => 1, 
    "to" => 3, 
    "data" => [ 
     [ 
     "id" => 5, 
     "status" => "Comeu Bem", 
     "created_at" => "2017-07-05 13:55:25", 
     "updated_at" => "2017-07-05 13:55:25", 
     ], 
    ], 
    ] 

但是,當我刪除了分頁,我得到的錯誤,但僅僅是因爲我加入了get()方法:

>>> App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) { 
...       return Carbon\Carbon::parse($row->created_at)->format('Y-m-d'); 
...      })->get(); 
PHP warning: strtolower() expects parameter 1 to be string, object given in D:\Joao\git\F1Softwares\Code\Server\F1Softwares\vendor\laravel\framework\src\Illuminate\Database\Grammar.php on line 58 
>>> 
>>> 
>>> App\Eating::Where('student_id', 2)->orderBy('created_at', 'DESC')->groupBy(function ($row) { 
...       return Carbon\Carbon::parse($row->created_at)->format('Y-m-d'); 
...      }); 
=> Illuminate\Database\Eloquent\Builder {#855} 

任何想法我可能做錯了什麼?我需要有orderBy和分頁,讓應用更容易顯示結果(這是一個RestFul調用)。

感謝, 若昂

回答

2

您必須調用一個集合groupBy()方法,但似乎這並不會與paginate()工作。你可以嘗試使用forPage()方法的集合:

App\Eating::where('student_id', 2)->orderBy('created_at', 'DESC') 
    ->get()->groupBy(function ($eating) { 
     return $eating->created_at->format('Y-m-d'); 
    })->forPage(1, 25); 

而且,只是一個說明,你不需要用碳來解析日期,雄辯做這個給你。


或者,你可以嘗試manually create your paginator一旦你使用Illuminate\Pagination\LengthAwarePaginator分組的集合。

$eatings = App\Eating::where('student_id', 2)->orderBy('created_at', 'DESC') 
       ->get()->groupBy(function ($eating) { 
        return $eating->created_at->format('Y-m-d'); 
       }); 
$paginatedEatings = new LengthAwarePaginator($eatings, $eatings->count(), 25); 

return $paginatedEatings->toArray(); 
+0

感謝您的回覆! 那個我失去了分頁結果的問題。 我確實需要next_page_link,但使用這種方法,我得到了數據分組,但沒有分頁。結果: => Illuminate \ Database \ Eloquent \ Collection {#891 all:[ 「2017-07-05」=> Illuminate \ Database \ Eloquent \ Collection {#909 all:[ App \ Eating {#945 ID:5, 狀態: 「Comeu貝姆」, created_at: 「2017年7月5日13點55分25秒」, }, ], }, –

+0

啊我現在怎麼沒看到分頁。 ..閱讀文檔後,儘管看起來你不能一起使用它們:「目前,使用groupBy語句的分頁操作不能被Laravel高效地執行,如果你需要使用帶有分頁結果集的groupBy,建議您查詢數據庫並手動創建分頁程序。「 https://laravel.com/docs/5.4/pagination – upful

+0

謝謝先生!這終於解決了我的問題! –