【问题标题】:Paginating Eloquent 4.2 models outside of Laravel在 Laravel 之外为 Eloquent 4.2 模型分页
【发布时间】:2016-02-28 20:43:52
【问题描述】:

我在 Laravel 之外使用 Eloquent 4.2(在 Slim 2 应用程序中)并且有一个文章对象的集合(其中 15 个)我想使用 Laravel 分页库进行分页。

我已设法设置分页,但找不到如何以编程方式设置当前页面。

这是我目前的代码:

$articles = new Article;
$articles = $articles->orderBy('created_at', 'DESC');

$pagination = $articles->paginate(5);

foreach($pagination as $s) {
    dump($s);
}

dd($pagination);

foreach 循环产生 5 个 Article 实例,而 dd() 产生一个 LengthAwarePaginator 实例。

我的问题是,由于我只能访问第一页的数据,如何设置要读取的页面?

【问题讨论】:

    标签: php laravel pagination eloquent


    【解决方案1】:

    我发现了一种非常老套的方法来强制分页类在 Laravel 之外工作(因为奇怪的是,它似乎与框架非常紧密地耦合)。此方法允许您设置当前路径和页码 - 但遗憾的是不允许您使用 links() 等方法。代码如下:

    Paginator::currentPathResolver(function() use($id) { return $id; });
    Paginator::currentPageResolver(function() use($id) { return $id; });
    
    $articles = new Article;
    $articles = $articles->orderBy('created_at', 'DESC');
    $pagination = $articles->paginate(5);
    

    【讨论】:

    • 非常感谢!这很有帮助。
    【解决方案2】:

    你可以这样做。记得在执行查询之前设置分页

    //as for me i am using this, and it works fine, and we have the same laravel version 4.2
    \Paginator::setCurrentPage($current_page);
    
    $pagination = $articles->paginate(5);
    

    更新

    那就试试这个

    $articles = new Article;
    \Paginator::setCurrentPage($current_page);
    //you have to use $articles->orderBy instead of $articles = $articles->orderBy
    $articles->orderBy('created_at', 'DESC');
    $pagination = $articles->paginate(5);
    

    【讨论】:

    • 我试过这种方式,结果如下:致命错误:从上下文调用受保护的方法 Illuminate\Pagination\Paginator::setCurrentPage()
    • 我再次更新了我的答案。请检查。我想我现在明白你的问题是什么了。
    • 您在回答中提到您正在使用 Laravel - 我不是;只是口才。这有关系吗?
    • 我自己也不确定。抱歉,我不明白你在 Laravel 之外使用它。我一直在 laracast laracasts.com/index.php/discuss/channels/general-discussion/… 中查看论坛,上面写着“分页使用 Laravel 路由。所以你不能在 Laravel 应用程序之外使用它。”还有这个laravel.io/forum/04-28-2014-using-pagination?page=1
    【解决方案3】:

    对于那些使用 Illuminate Paginator 和作曲家的人来说,对下面的答案稍加修改。请注意调用的 LengthAwarePaginator 类:

    Pagination\LengthAwarePaginator::currentPathResolver(function() use($page) { return "/your_path"; });
    Pagination\LengthAwarePaginator::currentPageResolver(function() use($page) { return $page; });
    

    另外,你应该得到页面变量:

    $page = (isset($_GET['page']) ? $this->sanitize($_GET['page'], 'int') : 1);
    

    Sanitize 是我的功能之一,可以避开可能来自 URI 的恶意代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-06
      • 1970-01-01
      • 2015-09-11
      • 2019-09-16
      • 1970-01-01
      • 2013-12-27
      • 2021-01-16
      • 2023-04-03
      相关资源
      最近更新 更多