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: 错误:调用未定义的方法 IlluminateDatabaseEloquentCollection::paginate()
FatalErrorException: Error: Call to undefined method IlluminateDatabaseEloquentCollection::paginate()
我搜索了这个网站和许多其他网站,但不明白如何对集合进行分页.
I searched this and many other sites but cant understant how to paginate a collection.
感谢您的帮助
推荐答案
分页器必须获取它通常会使用偏移/限制语句从数据库查询中获取的项目.所以当你有一个包含所有项目的集合时,你应该自己做偏移/限制.
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屋!