diff --git a/src/ElasticEngine.php b/src/ElasticEngine.php old mode 100644 new mode 100755 index a5e0788..3e0e084 --- a/src/ElasticEngine.php +++ b/src/ElasticEngine.php @@ -315,7 +315,7 @@ public function map(Builder $builder, $results, $model) ->get($columns) ->keyBy($scoutKeyName); - return Collection::make($results['hits']['hits']) + $values = Collection::make($results['hits']['hits']) ->map(function ($hit) use ($models) { $id = $hit['_id']; @@ -331,6 +331,8 @@ public function map(Builder $builder, $results, $model) }) ->filter() ->values(); + + return $values instanceof Collection ? $values : Collection::make($values); } /** diff --git a/tests/ElasticEngineTest.php b/tests/ElasticEngineTest.php index 7be7c4d..29ef7b2 100644 --- a/tests/ElasticEngineTest.php +++ b/tests/ElasticEngineTest.php @@ -2,6 +2,7 @@ namespace ScoutElastic\Tests; +use Illuminate\Database\Eloquent\Collection; use ScoutElastic\Builders\FilterBuilder; use ScoutElastic\Builders\SearchBuilder; use ScoutElastic\ElasticEngine; @@ -440,6 +441,82 @@ public function testMapWithTrashed() ); } + public function testMapReturnDatabaseCollection() + { + $this->markTestSkipped(); + + $results = [ + 'hits' => [ + 'total' => 2, + 'hits' => [ + [ + '_id' => 1, + '_source' => [ + 'title' => 'foo', + ], + ], + [ + '_id' => 2, + '_source' => [ + 'title' => 'bar', + ], + ], + ], + ], + ]; + + $model = $this->mockModel([ + 'key' => 2, + 'methods' => [ + 'usesSoftDelete', + 'newQuery', + 'whereIn', + 'get', + 'keyBy', + ], + ]); + + $model + ->method('usesSoftDelete') + ->willReturn(false); + + $model + ->method('newQuery') + ->willReturn($model); + + $model + ->method('whereIn') + ->willReturn($model); + + $model + ->method('get') + ->willReturn($model); + + // The mocked `newQuery` chain will return an array of a single model (ID: 2) + // When mapping `$results['hits']['hits']`, the first item (ID: 1) will return null in `Collection::map()` + // This will result in `Collection::toBase()` being called, converting to a `Support\Collection` + $model + ->method('keyBy') + ->willReturn([ + 2 => $model, + ]); + + $builder = $this + ->getMockBuilder(FilterBuilder::class) + ->disableOriginalConstructor() + ->getMock(); + + $collection = $this->engine->map($builder, $results, $model); + + $this->assertSame( + [$model], + $collection->all() + ); + + // Assert that an `Eloquent\Database\Collection` is returned + $this->assertInstanceOf(Collection::class, $collection); + } + public function testGetTotalCount() { $results = [