Browse Source

Merge pull request #61 from fede91it/master

Update docs to explain collection hydration
master
Tom 8 years ago
committed by GitHub
parent
commit
fbe64c6978
  1. 9
      README.md

9
README.md

@ -120,16 +120,13 @@ This will, however, also return the `relevance` aliased column regardless of wha
## How to get a Laravel Eloquent Collection
Transforming the search results into a collection of Laravel Eloquent models is outside the scope of this project. However, an easy way to achieve this without hitting your database more than necessary is to use the Eloquent `fill()` method.
Transforming the search results into a collection of Laravel Eloquent models is outside the scope of this project. However, an easy way to achieve this without hitting your database more than necessary is to use the Eloquent `hydrate()` method.
```php
$users = collect(array_map(function($result) {
return (new \App\User())->forceFill(get_object_vars($result));
}, Searchy::users('name', 'email')->query('Andrew')->get()));
\App\User::hydrate(Searchy::users('name', 'email')->query('Andrew')->get());
```
All this does is map a function over the Searchy results and then creates a new instance of the User model and hydrates the model using the `forceFill()` method.
Then once it has an array of all the Eloquent User models, it simply uses the Laravel `collect()` method to return the array as Laravel Collection which is the same as you would receive from querying the Laravel model directly. `get_object_vars()` is simply a PHP method to extract the accessible object variables as an associative array.
This method creates a collection of models from a plain arrays. This is just our case because Searchy results are provided as arrays, and using `hydrate` we will converted them to instances of `User` model.
## Unicode Characters Support

Loading…
Cancel
Save