Skip to content

Commit c2d4c2d

Browse files
committed
fix: add lazy loading to lazyByCursor for eloquent queries (resolves #95)
1 parent 25b14d3 commit c2d4c2d

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

src/Eloquent/Mixins/BuilderLazyByCursor.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Tpetry\PostgresqlEnhanced\Eloquent\Mixins;
66

77
use Closure;
8+
use Generator;
89
use Illuminate\Database\Eloquent\Model;
910
use Illuminate\Support\LazyCollection;
1011

@@ -15,8 +16,17 @@ public function lazyByCursor(): Closure
1516
{
1617
return function (int $chunkSize = 1000): LazyCollection {
1718
/* @var \Illuminate\Database\Eloquent\Builder $this */
18-
return $this->applyScopes()->getQuery()->lazyByCursor($chunkSize)->map(function (object $record): Model {
19-
return $this->newModelInstance()->newFromBuilder((array) $record);
19+
return new LazyCollection(function () use ($chunkSize): Generator {
20+
foreach ($this->applyScopes()->getQuery()->lazyByCursor($chunkSize)->chunk($chunkSize) as $items) {
21+
$models = $this->getModel()->hydrate($items->all())->all();
22+
if (count($models) > 0) {
23+
$models = $this->eagerLoadRelations($models);
24+
}
25+
26+
foreach ($models as $model) {
27+
yield $model;
28+
}
29+
}
2030
});
2131
};
2232
}

0 commit comments

Comments
 (0)