在Eloquent中使用GroupBy和Pagination时出错

时间:2017-07-06 13:36:39

标签: mysql laravel pagination eloquent laravel-eloquent

我正在尝试使用eloquent让我按响应分组,同时给我一个Pagination响应(给我链接到第二页的那个)。 我正在尝试这样做:

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);

但是,我在Tinker中运行时遇到了这个错误:

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调用)。

谢谢, 若昂

1 个答案:

答案 0 :(得分: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);

另外,只需注意,您不需要使用Carbon来解析日期,Eloquent会为您执行此操作。

或者,您可以在使用Illuminate\Pagination\LengthAwarePaginator对收藏进行分组后尝试manually create your paginator

$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();