Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] How to include custom attributes in search results? #150

Closed
freeku opened this issue Dec 30, 2020 · 2 comments
Closed

[Question] How to include custom attributes in search results? #150

freeku opened this issue Dec 30, 2020 · 2 comments
Labels
enhancement New feature or request

Comments

@freeku
Copy link

freeku commented Dec 30, 2020

Does anyone know how to include custom attributes from the index into the model when returning search results?

I've added custom fields in the index using toSearchableArray and these are showing up when returning the raw results. However, when I use the ->get(), the custom fields are not included in the model objects (as they are not in the underlying database table), and I can't seem to find out how to include them.

@freeku freeku added the enhancement New feature or request label Dec 30, 2020
@matchish
Copy link
Owner

https://github.com/matchish/laravel-scout-elasticsearch#working-with-results

@freeku
Copy link
Author

freeku commented Jan 2, 2021

Thanks for the hint, Sergey!

For future reference for others looking into this, I've followed the approach outlined here #28 (comment) and added an additional function that's called in the getIterator() function:

private function mergeCustomFieldsIntoModels($eloquentHits, $raw){     
        return collect($eloquentHits)->map(function(Model $eloquentHit) use($raw){

            $raw = collect($raw)
                ->where('_source.__class_name', get_class($eloquentHit))
                ->where('_source.id', $eloquentHit->id)
                ->first()['_source'];
            
            $source = collect($raw);
            $eloquentHit->setAttribute('published_from', $source->get('published_from'));
            $eloquentHit->setAttribute('published_to', $source->get('published_to'));

            return $eloquentHit;
        })->all();
    }

@freeku freeku closed this as completed Jan 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants