【问题标题】:How to paginate a relationship result in laravel如何在laravel中对关系结果进行分页
【发布时间】:2020-06-30 19:36:34
【问题描述】:

下面一行是怎么分页的

$posts = Category::where('name', request('category'))->firstOrFail()->posts;

在下面的函数中

public function index()
    {
        $categories = category::all();

        if (request('category')) {
            $posts = Category::where('name', request('category'))->firstOrFail()->posts;

        } else {
            $posts = post::where('status', 1)->orderBy('created_at', 'DESC')->paginate(5);
        }


        return view('user.blog', compact('posts', 'categories'));
    }

【问题讨论】:

    标签: laravel eloquent pagination


    【解决方案1】:

    您必须使用实际的关系方法才能访问查询生成器:

    $posts = Category::where('name', request('category'))
        ->firstOrFail()
        ->posts()
        ->paginate(5);
    

    请参阅 Relationship Methods Vs. Dynamic Properties 上的 Eloquent 文档以供参考。

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 2015-02-16
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 2014-11-23
      • 2019-06-24
      相关资源
      最近更新 更多