我在数据库中有一个表,它每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>

推荐答案

一个建议的解决方案是缓存快照.让我解释一下我的观点.

当用户访问您的页面时,判断URL查询中的page参数.如果它不存在,或者如果它的值等于1,那么您应该刷新快照,方法是使用Cache::forget()方法通过其UICC删除旧快照.

然后,您需要生成一个新的UICC,用作新快照的标识符,并缓存新数据库查询的结果.

之后,您将从缓存而不是数据库中检索结果.

public function index(Request $request)
{
    if (! $request->has('page') || $request->integer('page') === 1) {
        $snapshot_id = session('snapshot_id');
        $key = "snapshots:$snapshot_id";
        if (Cache::has($key)) {
            Cache::forget($key);  // erase the snapshot from the cache in case it exists
        }

        $snapshot_id = Str::uuid();
        session(['snapshot_id' => $snapshot_id]); // store the snapshot id for later access

        $results = Data::all();
        Cache::forever("snapshots:$snapshot_id", $results); // cache the results inside the new snapshot
    }

    $snapshot_id = session('snapshot_id'); // retrieve the snapshot id
    $data = Cache::get("snapshots:$snapshot_id"); // get the snapshot data using the snapshot id
    $data = collect($data); // convert the data into a collection

    $per_page = 5;

    return $data->forPage($request->page, $per_page);
}

Laravel相关问答推荐

Laravel Livewire与自定义JS有关的多姆问题

我应该如何使用遵循依赖反转原则的工厂方法设计模式

laravel如何在Blade 模板中将元素添加到数组

spatie 包 laravel-tags 在迁移中没有 down() 函数是有原因的吗

Npm run dev 卡在 APP_URL

Laravel 集合排序不生效

如何在 Laravel 中使用内存数据库的完整测试套件之前迁移和 seeder ?

为什么 Laravel 5 会自动更新我的日期字段?

Laravel 监听器监听多个事件

Laravel 中未加密的 cookie

调用未定义的方法 Maatwebsite\Excel\Excel::load()

Laravel 动作未定义

Laravel 同步错误

laravel:Eloquent的例子将数据插入数据库

在 Laravel 中,如何获取 *only* POST 参数?

如何在 Laravel Mix 中将公共路径更改为包含下划线的内容?

Laravel 检测手机/平板电脑并加载正确的视图

Laravel 在域和子域中共享 cookie 检测问题

如何在不要求用户登录 Laravel 的情况下验证Electron邮件

Laravel 4 控制器模板/Blade - 正确的方法?