>当我尝试对从登录用户传递的结果进行分页时,出现错误:
$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::p aginate()
问题是什么,如何对对象数组进行分页?
试试这个:
$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);
分页方法必须是链中的最后一个元素,如>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
的实例。你需要做一些类似的事情
$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
}));
这样,您可以在分页对象中设置新项目,这些项目是来自数据库的分组结果。