laravel 4分页收集 [英] laravel 4 paginate collection
问题描述
我无法使用laravel 4创建合适的分页系统.我具有以下返回集合的模型和函数:
I cant create a proper pagination system using laravel 4. I have the following models and function that return collections:
模型餐厅:
public function fooditem()
{
return $this->hasMany('Fooditem','rest_id');
}
public function get_rest_foods($id){
return Restaurant::find($id)->fooditem->toArray();
}
第二个函数以数组的形式返回某个餐厅的所有食物.我也在API调用中使用了它.
The second function returns all food items for a certain restaurant as an array. I also use this in an API call.
在我的控制器中,我有这个:
in my controller i have this:
$food = $food->get_rest_foods($id);
$paginator = Paginator::make($food, 10, 5);
我将分页器传递到视图,它显示了链接,但还显示了我来自食物阵列的所有商品.
I pass the paginator to the view and it shows the links ok but also shows all my item from the food array.
我尝试使用
public function get_rest_foods($id){
return Restaurant::find($id)->fooditem->paginate(5);
}
但是我得到一个错误:
FatalErrorException:错误:调用未定义的方法Illuminate \ Database \ Eloquent \ Collection :: paginate()
FatalErrorException: Error: Call to undefined method Illuminate\Database\Eloquent\Collection::paginate()
我在这个网站和许多其他网站上进行了搜索,但无法确定如何对集合进行分页.
I searched this and many other sites but cant understant how to paginate a collection.
感谢您的帮助
推荐答案
分页程序必须使用offset/limit语句获取通常从数据库查询中获得的项目. 因此,当您拥有一个包含所有项目的集合时,应该自己进行偏移/限制.
The paginator must get the items that it would normally get from a database query with an offset/limit statement. So when you have a collection with all items, you should do the offset/limit yourself.
$food = $food->get_rest_foods($id);
$page = 1;
if( !empty(Input::get['page']) ) {
$page = Input::get['page'];
}
$perPage = 15;
$offset = (($page - 1) * $perPage);
$food = Paginator::make($food->slice($offset,$perPage, true)->all(), $food->count(), $perPage);
这篇关于laravel 4分页收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!