Laravel教程:如何对持续更新的数据实现控制器端分页
问题说明
数据库内有一张表每分钟都会持续更新,包含新增行、更新现有行等操作。需要实现以下逻辑:
- 用户首次加载页面时,由Controller创建一份数据快照
- 用户点击blade文件中的「加载更多」按钮时,从该快照中加载数据
- 用户刷新页面时,重新根据数据库最新数据生成快照
尝试多种方法均未成功,以下是最近的尝试代码:
MyController.php
public function index(Request $request) { // 生成唯一快照ID $snapshotId = $request->session()->get('snapshotId', uniqid('snapshot_', true)); // 判断当前请求是首次加载还是后续的「加载更多」请求 $isInitialLoad = !$request->has('page'); // 首次加载时,存储快照ID并清除之前的数据标识符 if ($isInitialLoad) { $request->session()->put('snapshotId', $snapshotId); $request->session()->forget('dataIdentifiers'); } .... 自定义数据查询逻辑 .... // 根据当前查询状态获取数据主键标识符 $identifiers = $dataQuery->pluck('id'); // 首次加载时,将标识符数组存储到会话中 if ($isInitialLoad) { $request->session()->put("dataIdentifiers_{$snapshotId}", $identifiers->toArray()); } else { // 「加载更多」请求时,从会话中取出存储的标识符数组 $identifiers = $request->session()->get("dataIdentifiers_{$snapshotId}"); } // 从快照标识符中截取当前页的数据ID,进行分页查询 $currentPageIdentifiers = $identifiers->slice(($request->input('page', 1) - 1) * 10, 10); $data = Data::whereIn('id', $currentPageIdentifiers)->get(); }
Blade模板中的加载更多按钮代码
<div class="container"> ...... </div> @php $dataIdentifiers = session('dataIdentifiers_' . $snapshotId); $dataIdentifiersCount = is_array($dataIdentifiers) ? count($dataIdentifiers) : 0; @endphp @if ($dataIdentifiersCount > count((array) $data)) <div class="text-center"> <button id="load-more" data-next-page="{{ session('currentPage', 1) + 1 }}" data-snapshot-id="{{ $snapshotId }}" class="btn btn--theme fw-bolder px-5">加载更多</button> </div> @endif <script> $(document).ready(function() { $('#load-more').click(function() { const nextPage = $(this).data('next-page'); const snapshotId = $(this).data('snapshot-id'); const url = `/my/controller/route?page=${nextPage}&snapshotId=${snapshotId}`; fetch(url) .then(response => response.json()) .then(data => { console.log(data); $('.container').append(data.html); }).catch(error => console.error('加载更多数据出错:', error)); }); }); </script>
内容的提问来源于stack exchange,提问作者AJK
相关产品推荐
相关产品推荐

