diff --git a/src/Searchable/DefaultImportSource.php b/src/Searchable/DefaultImportSource.php index 0de226b9..5aadedf6 100644 --- a/src/Searchable/DefaultImportSource.php +++ b/src/Searchable/DefaultImportSource.php @@ -50,7 +50,7 @@ public function searchableAs(): string public function chunked(): Collection { $query = $this->newQuery(); - $totalSearchables = $query->count(); + $totalSearchables = $query->toBase()->getCountForPagination(); if ($totalSearchables) { $chunkSize = (int) config('scout.chunk.searchable', self::DEFAULT_CHUNK_SIZE); $totalChunks = (int) ceil($totalSearchables / $chunkSize); diff --git a/tests/Integration/Searchable/DefaultImportSourceTest.php b/tests/Integration/Searchable/DefaultImportSourceTest.php index caa8eaf4..d4fb35c5 100644 --- a/tests/Integration/Searchable/DefaultImportSourceTest.php +++ b/tests/Integration/Searchable/DefaultImportSourceTest.php @@ -27,6 +27,23 @@ public function test_new_query_has_injected_scopes() $products = $source->get(); $this->assertEquals($iphonePromoUsedAmount, $products->count()); } + + public function test_chunked_with_complex_scope() + { + $dispatcher = Product::getEventDispatcher(); + Product::unsetEventDispatcher(); + + factory(Product::class, 2)->states(['iphone', 'promo', 'used'])->create(); + factory(Product::class, 3)->states(['kindle', 'promo', 'new'])->create(); + factory(Product::class, 2)->states(['iphone', 'promo', 'used'])->create(); + + Product::setEventDispatcher($dispatcher); + + $source = new DefaultImportSource(Product::class, [new ComplexScopeWithGroupBy()]); + $results = $source->chunked(); + + $this->assertEquals(7, $results->sum(fn ($chunk) => $chunk->get()->count())); + } } class UsedScope implements Scope @@ -43,3 +60,15 @@ public function apply(Builder $builder, Model $model) $builder->where('type', 'used'); } } + +class ComplexScopeWithGroupBy implements Scope +{ + public function apply(Builder $builder, Model $model) + { + // Just a simple example where we duplicate all products + // and de-duplicate them by grouping on the id. + $builder + ->leftJoin('products as products2', 'products.id', '=', 'products2.id') + ->groupBy('products.id'); + } +}