catzilla / scout-noindex

此包提供了在使用 Laravel Scout 时防止索引某些模型字段的一种简单方法。

v0.1.0 2018-09-03 11:07 UTC

This package is auto-updated.

Last update: 2024-09-18 05:45:46 UTC


README

GitHub license

此包提供了在使用 Laravel Scout 时防止索引某些模型字段的一种简单方法。

默认情况下,每次你保存 Eloquent 模型时,都会触发 saved 事件。结果,即使模型中没有发生变化,也会调度 MakeSearchable 任务(参见 Scout 的问题 #285)。

例如

// Retrieving first entry from database
$model = User::first();
// Nothing changed here, saving model
$model->save();
// Database query not performed, but MakeSearchable job dispatched

另一种情况,当你只想通过某些字段搜索模型,例如通过 namelogin。你更改了其他内容,但 MakeSearchable 任务仍会调度

// Retrieving first entry from database
$model = User::first();
// Changing email (NOT name or login)
$model->email = 'mail@example.com';
// Saving model
$model->save();
// email field updated, and MakeSearchable job dispatched even if we don't need to search by email

此包以简单的方式帮助解决这些问题。

安装

您可以通过 Composer 安装此包

composer require catzilla/scout-noindex

用法

在你的模型文件中,只需将 Searchable 特性替换为该包提供的特性。

可选,您可以使用 $index$noindex 属性来包含或排除搜索同步的字段。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Catzilla\ScoutNoindex\Searchable;

class User extends Model
{
    use Searchable;
    
    /**
     * Array of fields to search.
     * When this property present in model, only this fields will be searchable
     *
     * @var array
     */
    protected $index = [
        'name',
        'login'
    ];
    
    /**
     * Array of fields to exclude from syncing.
     * When this property present in model, any changes in this fields will not trigger search syncing.
     *
     * @var array
     */
    protected $noindex = [
        'email',
        'updated_at'
    ];
}

许可证

scout-noindex 采用 MIT 许可证 许可。