From 9a8d8568af0023cee2b24c56967388f4f8cda410 Mon Sep 17 00:00:00 2001 From: Jade Geels Date: Thu, 13 Feb 2025 14:31:01 +0100 Subject: [PATCH 1/2] Use getCountForPagination for query count --- src/Searchable/DefaultImportSource.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Searchable/DefaultImportSource.php b/src/Searchable/DefaultImportSource.php index 0de226b..5aadedf 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); From 8d4c10babe9f33ecc48c146059627a37e46df0ab Mon Sep 17 00:00:00 2001 From: Roy Duineveld Date: Thu, 20 Feb 2025 14:04:15 +0100 Subject: [PATCH 2/2] Tests --- .../Searchable/DefaultImportSourceTest.php | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/Integration/Searchable/DefaultImportSourceTest.php b/tests/Integration/Searchable/DefaultImportSourceTest.php index caa8eaf..d4fb35c 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'); + } +}