2017-02-22 87 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