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 要注意主表的使用有序的主键

相关推荐
DARLING Zero two♡1 小时前
接入 AI Ping 限免接口,让 GLM-4.7 与 MiniMax-M2.1 成为你的免费 C++ 审计专家
开发语言·c++·人工智能
码界奇点1 小时前
Java外功核心7深入源码拆解Spring Bean作用域生命周期与自动装配
java·开发语言·spring·dba·源代码管理
CRMEB-嘉嘉1 小时前
CRMEB私域会员电商系统pro-用户等级
php
老华带你飞1 小时前
考试管理系统|基于java+ vue考试管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
2501_921649491 小时前
股票 API 对接,接入美国纳斯达克交易所(Nasdaq)实现缠论回测
开发语言·后端·python·websocket·金融
程序喵大人1 小时前
constexpr
开发语言·c++·constexpr
Larry_Yanan1 小时前
Qt多进程(五)QUdpSocket
开发语言·c++·qt·学习·ui
Grassto1 小时前
从 GOPATH 到 Go Module:Go 依赖管理机制的演进
开发语言·后端·golang·go
懒惰蜗牛1 小时前
Day66 | 深入理解Java反射前,先搞清楚类加载机制
java·开发语言·jvm·链接·类加载机制·初始化
hudawei9961 小时前
flutter路由传参接收时机
开发语言·flutter·异步