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