问题
When I use the paginate
method with the following statement:
$user = User::where('id', 1)->first();
$images = $user->images->paginate(3);
I get the following error:
Method Illuminate\Database\Eloquent\Collection::paginate does not exist
However when I call it with the following statement:
$images = Image::where('user_id', $user->id)->paginate(3);
It works accordingly... I'm fairly new to Laravel, so forgive my ignorance, but what is the cause of the difference in results? Don't both statement return collections?
回答1:
paginate
is a method of the query builder not the collection. If you want to paginate the collection you need to do manual pagination:
$imagesPage = new LengthAwarePaginator($user->images->forPage($page,3), $user->images->count(), 3, $page); //Where $page is the current page number
Alternatively you can paginate the query builder:
$images = $user->images()->paginate(3);
Note that if you use the 2nd approach you don't need to eager load the images.
来源:https://stackoverflow.com/questions/50226653/proper-use-of-laravels-paginate-method