2015-12-22 169 views
1

使用->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();方法分頁結果後返回總數?

回答

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); 
} 
+0

因此,沒有像其他的簡單方法嗎? :/ 那很糟。不管怎麼說,還是要謝謝你! – senty

+0

這是我知道的最簡單的方法,如果你看代碼,反正很簡單 –