在 laravel 中通过子查询分页

Paginate through subquery in laravel

以下代码将正确输出前 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

使用

{{ $category->links() }}

$category 应该是您传递给 blade 的变量名。


示例

如果你像这样传递数据 return view('viewName', ['names' => $names]); 那么你必须使用 {{ $names->links() }}


Read this Laravel documentation

改为使用 simplePaginate 函数

$category = Category::select()
->where('slug', $slug)
->with(['webshops' => function ($query) {
    $query->groupBy('webshops.id')
    ->orderBy('webshops.name')
    ->with(['brands' => function ($query) {
        $query->where('active', 1)
        ->where('replace_by', NULL)
        ->orderBy('name');
    }])
    ->simplePaginate(3);
}])
->first();

你可以创建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);