【问题标题】:Adding data to Paginated Results将数据添加到分页结果
【发布时间】:2016-03-28 22:34:50
【问题描述】:

使用->find($id) 在变量中存储查询后添加数据非常简单。我可以使用..

 $photo = Photo::with('likes')->find($id);
 $photo->total_likes = $photo->likes->count();

 return response()->json($photos, 200);

像魅力一样工作。所以我不需要使用 for 循环


但是,如果我想向分页结果中添加数据怎么办?

$photos = Photo::with('likes')->where('user_id', $user_id)->paginate(15);

return response()->json($photos, 200);

这样,我收到的数据作为回报:

"total": 5,
"per_page": 15,
"current_page": 1,
"last_page": 1,
"next_page_url": null,
"prev_page_url": null,
"from": 1,
"to": 5,
"data": [
    "likes": [each like object..]
       ]

如何在分页结果后使用$photo->total_likes = $photo->likes->count(); 方法返回总计数?

【问题讨论】:

    标签: php laravel pagination eloquent lumen


    【解决方案1】:

    您可以通过创建自定义分页器实例来实现此目的。例如:

    public function getNews() {
        $news = \App\News::select()->orderBy('created_at', 'desc')->get();
    
        $collection = $this->prepareNews($news);
    
        return $this->paginator($collection);
    }
    
    protected function prepareNews($news) {
        // do stuff with your news/whatever here
        foreach($news as $item) {
             'title' => $item->title,
             'category' => $item->category_id != 0 ? $categories[$item->category_id]['name'] : null,
        }
        // Note the collect, this is important 
        return collect($arr);
    }
    
    protected function paginator(\Illuminate\Support\Collection $items, $perPage = 3) {
        //Get current page form url e.g. &page=6
        $currentPage = Paginator::resolveCurrentPage() - 1;
        $currentPageSearchResults = $items->slice($currentPage * $perPage, $perPage)->all();
    
    
        return new Paginator($currentPageSearchResults, count($items), $perPage);
    }
    

    【讨论】:

    • 那么就没有其他简单的方法了吗? :/ 那很糟。还是谢谢!
    • 这是我知道的最简单的方法,如果你看一下代码,无论如何都很容易
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多