当前位置: 首页 > news >正文

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

http://www.dtcms.com/a/303383.html

相关文章:

  • 软件工程:阿里巴巴Java编程手册
  • CCCS作为主要起草人参与《信息技术 智能语音交互系统 第3部分:智能客服》国家标准修订
  • 阿里云 【免费试用】MCP 赋能可视化 OLAP 智能体应用
  • 『 C++ 入门到放弃 』- 哈希表
  • 微积分 | dx / dy 不是比率吗?
  • 《C++继承详解:从入门到理解公有、私有与保护继承》
  • ffmpeg-7.1.1 下载安装 windows 版,MP4 转 m3u8 切片,遇到报错 Unrecognized option ‘vbsf‘的解决办法
  • Linux:理解操作系统
  • 数据结构(动态数组)
  • PyTorch中flatten()函数详解以及与view()和 reshape()的对比和实战代码示例
  • DevOps时代的知识治理革命:Wiki如何成为研发效能的新引擎
  • GPT Agent与Comet AI Aent浏览器对比横评
  • Anaconda创建环境报错:CondaHTTPEFTOT: HTTP 403 FORBIDDEN for url
  • 力扣 之 最小覆盖子串(变长滑动窗口,越短越好)
  • 推客系统全链路架构设计与高并发实践:从CPS分佣到社交裂变
  • ARM双频RFID读写系统的设计
  • 【快捷指令】ios/macos快捷指令如何调用api接口(json请求例子)
  • 从“数字鸿沟”到“数字红利”:智慧养老如何让老人跨越技术门槛
  • MBR和GPT分区的区别
  • C语言-数组:数组(定义、初始化、元素的访问、遍历)内存和内存地址、数组的查找算法和排序算法;
  • 导入Maven项目
  • 解决幻读问题
  • maven 打包报错 process terminated
  • 基于Spring Boot+Vue的吉他社团系统设计和实现(协同过滤算法)
  • 架构师增效指南:飞算JavaAI:需求驱动下的智能微服务拆分与治理
  • 五自由度磁悬浮轴承转子不平衡质量的高性能控制策略全解析
  • 亚马逊地址关联暴雷:新算法下的账号安全保卫战
  • 采用黑翅鸢优化算法BKA-CNN-LSTM、CNN-LSTM、LSTM、CNN四模型多变量回归预测,多输入单输出(Matlab)
  • 《计算机“十万个为什么”》之 [特殊字符] 序列化与反序列化:数据打包的奇妙之旅 ✈️
  • Python与Mysql