laravel chunkById导出数据乱序问题

2025年7月28日17:47:29

这几天在做数据导出优化,使用xlswriter作为导出组件,但是发现在 使用

$base->chunkById(2000, function ($list) use ($writer, $sheet1) {

发现导出的数据是乱的,偶尔有些重复,偶尔有些少了,很奇怪,把数据打印出来的时候,发现模型的主表的id是乱序的

查看了一下chunkById的代码

复制代码
public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
    {
        $this->orders = $this->removeExistingOrdersFor($column);

        if (! is_null($lastId)) {
            $this->where($column, '>', $lastId);
        }

        return $this->orderBy($column, 'asc')
            ->limit($perPage);
    }

这里用的是id的 > 所以说,主表的id是 主键,但是返回的id是乱序,导出的数据就是乱的,

这里使用chunk方法是使用forpage

复制代码
public function chunk($count, callable $callback)
    {
        $this->enforceOrderBy();

        $page = 1;

        do {
            // We'll execute the query for the given page and get the results. If there are
            // no results we can just break and return from here. When there are results
            // we will call the callback with the current chunk of these results here.
            $results = $this->forPage($page, $count)->get();

            $countResults = $results->count();

            if ($countResults == 0) {
                break;
            }

            // On each chunk result set, we will pass them to the callback and then let the
            // developer take care of everything within the callback, which allows us to
            // keep the memory low for spinning through large result sets for working.
            if ($callback($results, $page) === false) {
                return false;
            }

            unset($results);

            $page++;
        } while ($countResults == $count);

        return true;
    }

所以可以避免导出数据混乱的问题,这里使用 chunkById 要注意主表的使用有序的主键

相关推荐
维吉斯蔡6 小时前
【VS Code / Cursor】文件夹右键快捷打开与文件类型自动关联
开发语言·程序人生·学习方法
漏刻有时7 小时前
PHP GeoJSON转PNG地图渲染程序开发笔记、源码解读、问题复盘与整改方案
android·笔记·php
luj_17688 小时前
星火科技助力边远地区防病攻坚
c语言·开发语言·c++·经验分享·算法
always_TT8 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
xcLeigh9 小时前
Go入门:变量声明的五种方式详解
java·开发语言·golang
zmzb01039 小时前
C++课后习题训练记录Day175
开发语言·c++
脱胎换骨-军哥10 小时前
C++ 代码规范与格式化指南
开发语言·c++·代码规范
枕星而眠11 小时前
C++ STL Map容器完全指南:从有序红黑树到无序哈希表
java·开发语言
爱吃牛肉的大老虎11 小时前
Rust对象之结构体,枚举,特性
开发语言·后端·rust
bbq粉刷匠12 小时前
HashMap 底层原理深度拆解(二):putVal 完整链路解析(懒加载 · 链表遍历 · 尾插法)
java·开发语言·哈希算法