php - 获取分页 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 个文件..
解决方案
如果我理解正确,您希望检索所有可能页面的结果。如果是这样,您可以改用模型块。这就是它在您的情况下的工作方式:
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 个结果块和当前页面将被传递到。
您应该在此处查看有关块方法的更多信息
我希望这有帮助。
推荐阅读
- java - 为什么当我将元素绑定到其中时,我的代码总是收到空指针异常?我在 Android Studio 中使用 Java
- elasticsearch - 多个词在搜索中充当单个词 - Elasticsearch
- swift - 在 swift 中使用 DispatchWorkItem 有什么好处?
- c - 机器指令中的 LEAL 和 MOVL
- reactjs - reactjs:在进行推送呼叫后,连接路由器不会重定向用户
- git - 无法使用 SSH 密钥从远程服务器访问 bitbucket 以对存储库中的最新代码执行 git pull
- javascript - 更新图表数据,但并非所有条形图都重绘
- jquery - 如何显示日期来自 jQuery instated 的显示当前日期?
- html - 无法调用 Django 函数在 postgres db 中插入数据
- .net-core - 从异步方法返回字符串