我有相关产品的模型类别:
public function products()
{
return $this->hasMany(Product::class);
}
在MainController中,我有代码:
$products = Category::with('products')->whereNull('parent_id')->paginate(15);
仅对方法类别进行分页,但是如何对产品进行分页?
答案 0 :(得分:0)
在另一个分页中使用分页并不是一个好主意,但是,如果要执行此操作,则应该为每个类别的产品创建manual pagination:
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Http\Request;
$categories = Category::with('products')->whereNull('parent_id')->paginate(15);
foreach ($categories as $category) {
$count = $category->products->count(); // total count of products in this category
$limit = 10; // count of products per page in child pagination
$page = $request->input('category'.$category->id.'page', 1); // current page of this category's pagination
$offset = ($page * $limit) - $limit; // offset for array_slice()
$itemsForCurrentPage = array_slice($category->products->toArray(), $offset, $limit, true);
$paginator = new Paginator($itemsForCurrentPage, $count, $limit, $page, [
'path' => $request->url(),
'query' => $request->query(),
]);
$paginator->setPageName('category'.$category->id.'page');
$category->paginator = $paginator;
}
return view('categories.index', ['categories' => $categories]);
然后在您的categories\index.blade.php
中:
<ul>
@foreach ($categories as $category)
<li>
<h3>{{ $category->title }}</h3>
@if ($category->paginator)
<ul>
@foreach ($category->paginator->items() as $product)
<li>{{ $product['title'] }}</li>
@endforeach
</ul>
{{ $category->paginator->links() }}
@endif
</li>
@endforeach
</ul>
{{ $categories->links() }}
我希望这会有所帮助,但我再说一遍,在另一个分页中使用分页并不是一个好主意。