【问题标题】:Laravel simplePaginate() for Grouped DataLaravel simplePaginate() 用于分组数据
【发布时间】:2019-06-26 03:24:21
【问题描述】:

我有以下问题。

$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() 期望参数 1 是字符串,给定对象

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

【问题讨论】:

    标签: laravel eloquent laravel-collection


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      问题解决了。我通过这个例子创建了自定义分页器: https://stackoverflow.com/a/30014621/6405083

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

      【讨论】:

        【解决方案3】:

        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 方面的帮助,您能否提供一个您期望的结果示例和一个数据库结构示例?

        【讨论】:

        • Carbon::parse 再次创建一个对象。这将正确分页。
        • Method Illuminate\Database\Eloquent\Collection::simplePaginate does not exist.
        【解决方案4】:

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

        你可以试试:

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

        【讨论】:

        • 我无法按原始created_at 字段 进行分组...我需要先将其格式化为'Y-m-d'...看看我的第一篇文章。我已经更新了问题描述
        猜你喜欢
        • 2017-09-16
        • 2023-04-07
        • 1970-01-01
        • 2013-06-10
        • 2018-08-26
        • 1970-01-01
        • 2022-11-02
        • 2018-11-19
        • 2021-11-04
        相关资源
        最近更新 更多