2017-02-22 103 views
-1

許多關係,我有兩個型號Laravel分頁到了在Laravel 5.4

專輯

public function AlbumImage(){ 

     return $this->hasMany('App\AlbumGallery'); 
    } 

AlbumGallery

在控制器我有以下代碼

$data= Album::where('id', $id)->with('AlbumImage')->first(); 

現在我需要分頁只有專輯畫廊。我曾嘗試以下方法,但它不工作

$data= Album::where('id', $id)->with('AlbumImage')->first()->paginate(2); 

也試過這個問題的答案 Laravel Eloquent pagination on relationships

+0

您正在使用哪種laravel版本? – davejal

+0

laravel 5.4我使用 – iCoders

+0

描述不工作。 – davejal

回答

1

所以給人對於your mentioned answer,添加到您的Album型號:

public function getAlbumImagePaginatedAttribute() 
{ 
    return $this->AlbumImage()->paginate(3); 
} 

而在刀片使用的視圖文件是這樣的:

{{ $album->name }}<br> 

<ul> 
@foreach($album->album_image_paginated as $album_gallery) 
    <li>{{ $album_gallery->gallery_name }}</li> 
@endforeach 
</ul> 

{{ $album->album_image_paginated->links() }} 

而對於API調用您可以使用這樣的事情:

Route::get('/albums/{id}', function($id) { 

    $album = \App\Album::findOrFail($id); 

    return [ 
     'id' => $album->id, 
     'images' => $album->album_image_paginated, 
    ]; 
}); 

因此,響應將是:

{ 
    "id":1, 
    "images":{ 
     "total":6, 
     "per_page":3, 
     "current_page":1, 
     "last_page":2, 
     "next_page_url":"http://example.app/api/albums/1?page=2", 
     "prev_page_url":null, 
     "from":1, 
     "to":3, 
     "data":[ 
     { 
      "id":1, 
      "gallery_name":"first image", 
      "album_id":1, 
      "created_at":"2017-02-22 09:47:46", 
      "updated_at":"2017-02-22 09:47:46" 
     }, 
     { 
      "id":2, 
      "gallery_name":"Second", 
      "album_id":1, 
      "created_at":"2017-02-22 09:48:31", 
      "updated_at":"2017-02-22 09:48:31" 
     }, 
     { 
      "id":3, 
      "gallery_name":"33", 
      "album_id":1, 
      "created_at":"2017-02-22 09:48:35", 
      "updated_at":"2017-02-22 09:48:35" 
     } 
     ] 
    } 
} 

希望這有助於!

+0

@Peter.thanks我試過在這個我面臨的問題是如果我點擊pagniation鏈接它不會chage專輯圖像。\ – iCoders

+0

@iCoders好的,也請確保點擊鏈接時,該網址實際上更改爲「http://example.app/api/albums/1?page=2」,因此它具有「page = 2」。還有,如果你有幾個實體應該被分頁,可能需要設置自定義'pageGallery'參數,以便paginator理解它 –

+0

@ Peter.Thanks.yapage url isd已經改變只有一件事是改變圖庫 – iCoders