【问题标题】:Eloquent paginate two relation merged雄辩的分页两个关系合并
【发布时间】:2018-11-04 20:21:24
【问题描述】:

我有两个模型:任务和评论

在我的用户配置文件中,我想显示任务和 cmets 按创建日期排序。

为此我会这样做:

$timeline_array = $customer->comments;
$timeline_array = $timeline_array->toBase()->merge($customer->tasks);

//sort timeline event
$timeline_array = $timeline_array->sortByDesc(function($timeline_event){
    return $timeline_event->created_at;
});

我在我的视图中 foreach 我的数组。它工作正常,但如果我有太多的 cmets 或任务,这将是一个很大的要求,所以我想添加一个分页器。

我该怎么做?

如果我最后有一个$timeline_array->paginate(5);,我会收到错误:

方法 Illuminate\Support\Collection::paginate 不存在。

而且我认为这并没有解决我的问题,因为我在分页之前加载了所有 cmets 和任务。

有人有想法/解决方案吗?

【问题讨论】:

    标签: laravel pagination eloquent relationship


    【解决方案1】:

    终于找到解决办法了:

    $timeline_array = $customer->comments;
    $timeline_array = $timeline_array->toBase()->merge($customer->tasks);
    
    //sort timeline event
    $timeline_array = $timeline_array->sortByDesc(function($timeline_event){
      return $timeline_event->created_at;
    });
    
    $item_per_page = 10;
    $timeline_array = new LengthAwarePaginator($timeline_array->forPage(Paginator::resolveCurrentPage(), $item_per_page), count($timeline_array), $item_per_page, Paginator::resolveCurrentPage(), [
      'path' => Paginator::resolveCurrentPath()
    ]);
    

    【讨论】:

      【解决方案2】:

      Paginate 方法仅适用于查询构建器或 eloquent , 有人在这里创建了一个要点,您可以在其中对数组或集合使用分页:

      https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb

      尝试像这样使用它:

      $timeline_array = $customer->comments;
      $timeline_array = $timeline_array->toBase()->merge($customer->tasks);
      
      //sort timeline event
      $timeline_array = $timeline_array->sortByDesc(function($timeline_event){
        return $timeline_event->created_at;
      });
      
      $timeline_array = $this->paginate($items);
      
      
      public function paginate($items, $perPage = 15, $page = null, $options = [])
      {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), 
        $items->count(), $perPage, $page, $options);
      }
      

      或者将其作为宏添加到您的应用服务提供程序中以进行更好的实践。

      【讨论】:

      • 这是正确的方法,但我需要使用LengthAwarePaginator 使其适用于我的项目,但谢谢!
      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2018-02-19
      相关资源
      最近更新 更多