我试图过滤一个分页的有说服力的集合,但是每当我使用任何一种集合方法时,都会丢失分页。
$models = User::orderBy('first_name','asc')->paginate(20);
$models = $models->each(function($model) use ($filters) {
if(!is_null($filters['type'])) {
if($model->type == $filters['type'])
return $model;
}
if(!is_null($filters['state_id'])) {
if($model->profile->state_id == $filters['state_id'])
return $model;
}
if(!is_null($filters['city_id'])) {
if($model->profile->city_id == $filters['city_id'])
return $model;
}
});
return $models;
我正在使用Laravel 4.2,有没有办法保持分页?
8条答案
按热度按时间8tntrjer1#
在Laravel 5.2+中可以回答标题问题:
如何在不丢失Paginator对象的情况下过滤Paginator的基础集合?
您可以按如下方式弹出、修改和插入集合:
Paginator构建在底层集合上,但实际上,当您使用任何继承的
Collection
方法时,它们返回底层集合,而不是完整的Paginator对象:集合方法返回用于将集合调用链接在一起的集合。daupos2t2#
用您的具体案例扩展mininoz的答案:
通过对SQL查询应用适当的条件,可以限制返回到PHP脚本的信息量,从而加快处理速度。
来源:http://laravel.com/docs/4.2/eloquent#querying-relations
velaa5lx3#
我有一个场景需要对集合进行筛选,我不能依赖查询生成器。
我的解决方案是示例化我自己的
Paginator
示例:然后在我的刀片模板中:
ajsxfq5m4#
paginate()是Builder的函数。如果你已经有了Collection对象,那么它没有paginate()函数,因此你不能轻易地将其恢复。
一种解决方法是使用不同的构建器来构建查询,这样以后就不需要过滤它了。Eloquent query builder是相当强大的,也许你可以把它拉下来。
另一种选择是自己构建自定义分页器。
ctzwtxfj5#
你可以在分页之前对你的模型做一些查询。
我想给予你一些想法。我会得到
all users by type
,sort
,最后做paginate
。代码看起来像这样。来源:http://laravel.com/docs/4.2/pagination#usage
blmhpbnm6#
这对我来说很合适;
kognpnkq7#
混合使用搜索参数和分页时的解决方案,因为默认分页不会保留搜索参数,使用GET:
示例生成的分页链接:http://myhost/context/list?过滤器1 =5&filtro_2=&filtro_3=&filtro_4=&filtro_5=&filtro_6&page=8
5us2dqdw8#
您可以在视图中简单地使用此格式
对于较新版本的Laravel,您可以使用以下命令: