正确使用 Laravel 的分页方法? [英] proper use of Laravel's paginate method?
问题描述
当我使用带有以下语句的 paginate
方法时:
When I use the paginate
method with the following statement:
$user = User::where('id', 1)->first();
$images = $user->images->paginate(3);
我收到以下错误:
方法 Illuminate\Database\Eloquent\Collection::paginate 没有存在
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);
它相应地工作......我对Laravel相当陌生,所以请原谅我的无知,但结果差异的原因是什么?两个语句都不返回集合吗?
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?
推荐答案
paginate
是查询构建器的一种方法,而不是集合.如果要对集合进行分页,则需要进行手动分页:
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.
这篇关于正确使用 Laravel 的分页方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!