Laravel 用于分组数据的 simplePaginate()

Laravel simplePaginate() for Grouped Data

我有以下查询。

$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy(function ($project) {
    return Carbon::parse($project->created_at)->format('Y-m-d');
})->simplePaginate(5);

当我尝试使用 simplePaginate() 方法分页时,出现此错误。

stripos() expects parameter 1 to be string, object given

在这种情况下如何对分组数据进行分页?

应该在查询而不是集合上调用分页方法。

你可以试试:

$projects = Project::orderBy('created_at', 'desc');
$data['sorted'] = $projects->groupBy('created_at');

created_at 属性已经转换为 Carbon 对象(默认情况下在 laravel 模型中)。这就是您收到该错误的原因。试试这个:

$projects = Project::orderBy('created_at', 'desc')->get();
$data['sorted'] = $projects->groupBy(function ($project) {
    return $project->created_at->format('Y-m-d');
})->simplePaginate(5);

此答案仅针对您遇到的错误。现在,如果您需要有关 QueryBuilder 的帮助,能否提供一个您期望的结果示例和一个数据库结构示例?

问题已解决。我是通过这个例子创建自定义分页器的:

$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
        $numPerPage = 15; // Number of results per page
        $count = Project::count(); // Get the total number of entries you'll be paging through
        // Get the actual items
        $projects = Project::orderBy('created_at', 'desc')
            ->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($project) {
                return $project->created_at->format('Y-m-d');
            });
        $data['sorted'] = new Paginator($projects, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);

simplePaginate 方法存在于以下路径中:

Illuminate\Database\Eloquent\Builder.php::simplePaginate()