Laravel Scout - 搜索垃圾记录并更新软删除模型

Laravel Scout - searching trashed records and keeping soft deleted models updated

默认情况下Laravel Scout will remove删除搜索索引中的任何模型,即使该模型是软删除的。

我们如何才能将模型保留在搜索索引中并更新它以具有 deleted_at 的当前时间戳而不是被删除?

关键在于 laravel-scout. First we should get familiar with the Searchable.php file, after-all it's the trait we apply to our model that kicks off all the magic. The methods searchable and unsearchable 的源代码非常清楚他们的目的。

现在注意两个静态方法enableSearchSyncing and disableSearchSyncing. This will let us control the syncing behavior. If we look back at the introduction到laravelscout,它给了我们这样的提示:

Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.

所以我们应该把注意力转向ModelObserver.php. This is where it all happens. The observer looks after four model events, created, updated, deleted, and restored

updatedrestored 只需调用 created 方法,该方法将检查是否确保同步未被禁用,然后 运行 $model->searchable() .

deleted,我们要防止的事情很相似。它将检查是否启用了同步,然后 运行 $model->unsearchable();.

解决方案:

既然我们了解了它的工作原理,那么要获得我们想要的效果就相对简单了。我们将从 scout 的书中取出一页,并在删除时使用 observers 更新我们的搜索索引。这是它的样子:

class UserObserver
{
    /**
     * Listen to the User deleting event.
     * 
     * @param User $user
     */
    public function deleting(User $user)
    {
        $user::disableSearchSyncing();
    }

    /**
     * Listen to the User deleted event.
     * 
     * @param User $user
     */
    public function deleted(User $user)
    {
        $user::enableSearchSyncing();

        $user->searchable();
    }
}

创建观察者后确保不要忘记将它添加到 AppServiceProvider 的启动方法中,否则它永远不会被注册。

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        User::observe(UserObserver::class);
    }

...

回顾一下这是如何工作的。在模型 deleteddeleting 事件)之前,我们告诉 scout 停止同步。然后当模型被删除时,我们re-enable同步,并调用searchable方法执行更新。我们在搜索数据库中的记录现在将使用正确的 deleted_at 时间戳进行更新。