我有两个型号
相册
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 :(得分: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"
}
]
}
}
希望这有帮助!