|
14 | 14 | namespace think\db; |
15 | 15 |
|
16 | 16 | use PDOStatement; |
| 17 | +use think\Collection; |
17 | 18 | use think\db\exception\DbException as Exception; |
18 | 19 | use think\model\LazyCollection as ModelLazyCollection; |
19 | 20 |
|
@@ -552,51 +553,15 @@ public function stream(callable $callback, bool $unbuffered = false): int |
552 | 553 | */ |
553 | 554 | public function chunk(int $count, callable $callback, string | array | null $column = null, string $order = 'asc'): bool |
554 | 555 | { |
555 | | - if ($count < 1) { |
556 | | - throw new Exception('The chunk size should be at least 1'); |
557 | | - } |
558 | | - |
559 | | - $options = $this->getOptions(); |
560 | | - $column = $column ?: $this->getPk(); |
561 | | - $bind = $this->bind; |
562 | | - |
563 | | - if ($this->getOption('order') || !is_string($column)) { |
564 | | - $times = 1; |
565 | | - $resultSet = $this->options($options)->page($times, $count)->select(); |
566 | | - } else { |
567 | | - $resultSet = $this->options($options)->order($column, $order)->limit($count)->select(); |
568 | | - |
569 | | - if (str_contains($column, '.')) { |
570 | | - [$alias, $key] = explode('.', $column); |
571 | | - } else { |
572 | | - $key = $column; |
573 | | - } |
574 | | - } |
575 | | - |
576 | | - while (true) { |
577 | | - if (false === call_user_func($callback, $resultSet)) { |
| 556 | + $chunks = $this->lazy($count, $column, $order)->chunk($count); |
| 557 | + |
| 558 | + foreach ($chunks as $chunk) { |
| 559 | + $result = $callback($chunk); |
| 560 | + if ($result === false) { |
578 | 561 | return false; |
579 | 562 | } |
580 | | - |
581 | | - if (count($resultSet) < $count) { |
582 | | - break; |
583 | | - } |
584 | | - |
585 | | - if (isset($times)) { |
586 | | - $times++; |
587 | | - $query = $this->options($options)->page($times, $count); |
588 | | - } else { |
589 | | - $end = $resultSet->pop(); |
590 | | - $lastId = is_array($end) ? $end[$key] : $end->getData($key); |
591 | | - |
592 | | - $query = $this->options($options) |
593 | | - ->limit($count) |
594 | | - ->where($column, 'asc' == strtolower($order) ? '>' : '<', $lastId); |
595 | | - } |
596 | | - |
597 | | - $resultSet = $query->bind($bind)->order($column, $order)->select(); |
598 | 563 | } |
599 | | - |
| 564 | + |
600 | 565 | return true; |
601 | 566 | } |
602 | 567 |
|
|
0 commit comments