以下代码将正确输出前 3 个网上商店:
public function category($slug) {
$category = Category::select()
->where('slug', $slug)
->with(['webshops' => function ($query) {
$query->groupBy('webshops.id')
->where('active', 1)
->orderBy('webshops.name')
->with(['brands' => function ($query) {
$query->where('active', 1)
->where('replace_by', NULL)
->orderBy('name');
}])
->paginate(3);
}])
->first();
if(!$category)
abort(404);
$data['title'] = "Tøjbutikker der forhandler ". $category->name;
$data['category'] = $category;
$data['webshops'] = $category->webshops;
return view('pages/category', $data);
}
Blade 模板:
<ul class="webshop-list">
@foreach($webshops as $webshop)
<li>
{{ $webshop->name }}
</li>
@endforeach
</ul>
{{ $webshops->links() }}
但是当我在 Blade 模板中插入分页代码时:
{{ $category->webshops->links() }}
我收到以下错误:
Method links does not exist.
我正在关注这里的文档: https://laravel.com/docs/5.4/pagination
最佳答案
您可以创建 paginator manually , 但如果你想保持代码的可维护性,只需使用两个集合:
$category = Category::where('slug', $slug)->first();
$shops = Webshop::whereHas('categories', function($q) use($category) {
$q->where('id', $category->id);
})
->groupBy('id')
->orderBy('name')
->with(['brands' => function ($query) {
$query->where('active', 1)
->where('replace_by', null)
->orderBy('name');
}])
->paginate(3);
关于php - 通过 laravel 中的子查询分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48012144/