algolia / scout-extended

Scout Extended: The Full Power of Algolia in Laravel
https://www.algolia.com/doc/framework-integration/laravel/getting-started/introduction-to-scout-extended/
MIT License
400 stars 87 forks source link

Index not automatically updated when shouldBeSearchable condition changes #235

Closed nfunwigabga closed 4 years ago

nfunwigabga commented 4 years ago

When the shouldBeSearchable condition changes, I expect the aggregated index to be reimported since this would affect the records that should be indexed. For instance, in Skill model:

class Skill extends Model
{
    ...
    public function shouldBeSearchable()
    {
        return (bool)$this->users()->count();
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'skill_user', 'skill_id', 'user_id');
    }
   ...
}

Then in my controller, when a user removes the skill from their profile or adds a skill to their profile, I would expect the shouldBeSearchable() to be checked again and the records reimported. eg

class UserSkillsController extends Controller
{
    ...
    public function updateSkills(Request $request)
    {
        auth()->user()->skills()->sync($request->skills);
    }
   ...
}

So assuming that a skill (eg public-speaking) has only one user, and in the above updateSkills function the user removed that skill from their profile, that leaves the skill with no user, so it should be removed from the index following the condition in the shouldBeSearchable() function.

aniplaylist commented 4 years ago

Have you tried adding $touches attribute to your Skill model?

Here's the documentation link : Updating relations when parent/child change

nfunwigabga commented 4 years ago

Yes I tried this and it still does not quite work. Seems to work for belongsTo relationships, but not for belongsToMany (which is what I have). I am currently using this package to observe the sync event and reimport. Not super efficient but works for now.

nfunwigabga commented 4 years ago

Ok, this issue on Laravel repo helped. Because I am dealing with a many-to-many relationship, I had to create a model for the intermediate table and place the $touches call in there. That way when there is a sync (which is actually updating the intermediate table), the Skill::class model also gets updated, which triggers Scout reindex.