ScoutEngines\Elasticsearch\ElasticsearchEngine::map PHP Method

map() public method

Map the given results to instances of the given model.
public map ( mixed $results, Model $model ) : Illuminate\Database\Eloquent\Collection
$results mixed
$model Illuminate\Database\Eloquent\Model
return Illuminate\Database\Eloquent\Collection
    public function map($results, $model)
    {
        if (count($results['hits']['total']) === 0) {
            return Collection::make();
        }
        $keys = collect($results['hits']['hits'])->pluck('_id')->values()->all();
        $models = $model->whereIn($model->getKeyName(), $keys)->get()->keyBy($model->getKeyName());
        return collect($results['hits']['hits'])->map(function ($hit) use($model, $models) {
            return $models[$hit['_id']];
        });
    }

Usage Example

 public function test_map_correctly_maps_results_to_models()
 {
     $client = Mockery::mock('Elasticsearch\\Client');
     $engine = new ElasticsearchEngine($client, 'scout');
     $model = Mockery::mock('Illuminate\\Database\\Eloquent\\Model');
     $model->shouldReceive('getKeyName')->andReturn('id');
     $model->shouldReceive('whereIn')->once()->with('id', ['1'])->andReturn($model);
     $model->shouldReceive('get')->once()->andReturn(Collection::make([new ElasticsearchEngineTestModel()]));
     $results = $engine->map(['hits' => ['total' => '1', 'hits' => [['_id' => '1']]]], $model);
     $this->assertEquals(1, count($results));
 }