我在数据库中有一个表,它每1min不断更新一次.添加新行、更新现有行等.当用户第一次加载页面时,Controller是否可能创建数据的"快照",以便当用户单击Blade 文件中的"加载更多"按钮时,从该快照加载数据.
当用户刷新页面时,将使用数据库中的更新数据重新创建快照.不知道从哪里开始.我试了很多方法都没有用.以下是我最近的try :
MyController.php
public function index(Request $request)
{
// Generate a unique snapshot ID
$snapshotId = $request->session()->get('snapshotId', uniqid('snapshot_', true));
// Check if this is the initial load or a subsequent "Load More" request
$isInitialLoad = !$request->has('page');
// On initial load, store the snapshot ID and clear previous identifiers
if ($isInitialLoad) {
$request->session()->put('snapshotId', $snapshotId);
$request->session()->forget('dataIdentifiers');
}
.... get my data ....
// Fetch identifiers (primary keys) based on the current state
$identifiers = $dataQuery->pluck('id');
// On initial load, store these identifiers in the session
if ($isInitialLoad) {
$request->session()->put("dataIdentifiers_{$snapshotId}", $identifiers->toArray());
} else {
// For "Load More", fetch the stored identifiers
$identifiers = $request->session()->get("dataIdentifiers_{$snapshotId}");
}
// Use the identifiers to query only the items in the snapshot for pagination
$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">Load More</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 loading more props:', error));
});
});
</script>