I am trying to create individual searchable arrays in Laravel Scout from a single City model, by iterating through its relationships. I have multiple fields returning arrays, all tied to the same hasMany relationship.
While Algolia can parse the arrays when returning search results, the presence of multiple arrays in the objects is causing the issue.
For instance, a current result is {city_name: 'Sydney', user_name: ['user_one', 'user_two'], user_id: [1, 2]}
. The intended result is two objects: {city_name: 'Sydney', user_name: 'user_one', user_id: 1}
and {city_name: 'Sydney', user_name: 'user_two', user_id: 2}
.
Region->cities is a many-to-many relationship, and Region->user is a one-to-many relationship.
Since toSearchableArray
returns a single searchable object, I've tried (unsuccessfully) to override it using searchable()
:
City.php:
public function users()
{
$regionIds = $this->regions()
->has('users') // filters regions with no users
->pluck('id');
return User::whereHas('regions', function($q) use ($regionIds) {
$q->whereIn('regions.id', $regionIds);
})->get(['name','id']);
}
public function toSearchableArray()
{
$array = $this->to_array;
foreach($this->users() as $user)
{
$array['user_name'] = $user->name;
$array['user_id'] = $user->id;
$array->searchable();
}
return [];
}
This returns Call to a member function searchable() on array
when I attempt to index, as searchable()
must be called on a query. I am trying to figure out a query that would allow me to attach a single User at a time via the Region relationship. Another possible option could be indexing the one object with the arrays, and building a splitter on both the user_name and user_id fields. Any help would be greatly appreciated!
source https://stackoverflow.com/questions/69382033/laravel-scout-multiple-searchable-arrays-from-one-model
Comments
Post a Comment