首页 > 解决方案 > 获取分页 Laravel 的总页数并写入文件页码

问题描述

我有一个代码:

 $posts = Post::paginate(100);

我怎样才能foreach分页页面并显示结果?我需要在每个文件中写一个帖子。

 foreach($posts as $page => $post) {
      //put on file current links posts of current page with file name: file-posts-$page.txt
 }

我该怎么做?

我试过:

for ($currentPage = $posts->perPage(); $currentPage <= $posts->total(); $currentPage++) {
   Paginator::currentPageResolver(function () use ($currentPage) {
            return $currentPage;
   });

   //put on file links of current posts of current page with file name: file-posts-$page.txt
}

但我不需要我的结果。我每 1 个帖子得到 1 个文件..

标签: phplaravel

解决方案


如果我理解正确,您希望检索所有可能页面的结果。如果是这样,您可以改用模型块。这就是它在您的情况下的工作方式:

Post::chunk(100, function(Collection $posts, $page) { 
  // Do what you want to do with the first 100 using $posts like this
  foreach($posts as $key => $post) {
   // Do stuff with $post
  }
  // You have access to $page here
  //put on file links of current posts of current page with file name: file-posts-$page.txt
});

由于您的每页是 100,我将 100 传递给 chunk 方法,该方法将检索前 100 个,然后是下一个 100,如此循环。传递给它的第二个参数是一个回调,每个 100 个结果块和当前页面将被传递到。

您应该在此处查看有关块方法的更多信息

我希望这有帮助。


推荐阅读