我有类别和项目表。每个项目只属于一个类别,每个类别有许多项目。因此,在类别模型中,我定义了这种关系:
public function items()
{ return $this->hasMany('Item', 'catid'); }
我用这种方式检索一个类别的数据:
$category = Category::find($id);
return View::make('admin.categories.catdetails')->with('category', $category);
在我看来,我可以循环浏览数据:
@foreach ($category->items as $item)
<tr>
<td> {{ $item->name }} </td>
<td> {{number_format($item->price, 2, '.', '')}} </td>
</tr>
@endforeach
但这会导致页面上的所有项目。在一页有这么多项目的情况下,如何使用laravel分页??我如何使用
::paginate() // in controller or model
->links() // in view
到目前为止,它抛出了很多错误,我无法理解。提前谢谢。
您可以在关系对象上调用paginate()
,您可以通过->items()
(而不是->items
)访问该对象
$items = $category->items()->paginate(10);
return View::make('admin.categories.catdetails')
->with('category', $category)
->with('items', $items);
那么在你看来:
@foreach ($items as $item)
和:
$items->links()
您可以使用属性访问器来实现您想要的内容。在您的模型中:
public function getPaginatedItemsAttribute(){
return $this->items()->paginate(10);
}
然后你这样使用它:
@foreach ($category->paginatedItems as $item)
和:
$category->paginatedItems->links()