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

相关推荐
TomCode先生2 小时前
c#动态树形表达式详解
开发语言·c#
高-老师2 小时前
基于R语言的物种气候生态位动态量化与分布特征模拟
开发语言·r语言·物种气候
大翻哥哥3 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
weixin_437830943 小时前
使用冰狐智能辅助实现图形列表自动点击:OCR与HID技术详解
开发语言·javascript·ocr
鹿鹿学长4 小时前
2025年全国大学生数学建模竞赛(C题) 建模解析|婴儿染色体数学建模|小鹿学长带队指引全代码文章与思路
c语言·开发语言·数学建模
zhousenshan4 小时前
Python爬虫常用框架
开发语言·爬虫·python
DKPT5 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
耶啵奶膘6 小时前
uni-app头像叠加显示
开发语言·javascript·uni-app
看海天一色听风起雨落6 小时前
Python学习之装饰器
开发语言·python·学习
Want5956 小时前
C/C++圣诞树①
c语言·开发语言·c++