首页 > 解决方案 > 使用“with”在关系中进行分页

问题描述

我在分页方面遇到了一些麻烦。我只需要用电影取一个类别并对其进行分页。现在我写了一些代码,但我认为它没有优化。

$category = Category::with(['movies' => function ($query) {
            $query->orderBy('id', 'desc')->paginate(18);
        }])->where('slug', $slug)->first();

        $catMoviesPaginate = $category->movies()->paginate(18);

标签: laravel

解决方案


你可以通过延迟加载来做到这一点,因为这里我提到了可以帮助你的代码。

$category = Category::where('slug', $slug)->first();
$movies= $category->movies()->paginate(18); //lazy loding.
return view('example', compact('category', 'movies'));

您也可以在视图文件中呈现分页。

@foreach ($movies as $movie)
    {{ $movie->id }}
@endforeach

{!! $movies->render() !!}

推荐阅读