esadewater/laravel-meilisearch

用于方便地处理 MeiliSearch 的搜索索引的包。

0.2.0 2024-03-11 20:56 UTC

This package is auto-updated.

Last update: 2024-09-08 02:43:03 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

通过 Laravel Scout 方便地处理 MeiliSearch 的搜索索引设置,如可排序和可筛选属性。

先决条件

您需要安装并配置好 Laravel Scout。如果您还没有做,您可以在设置一切的时候跳过 "配置可筛选数据和索引设置(Meilisearch)" 部分。

安装

您可以通过 composer 安装此包。

composer require esadewater/laravel-meilisearch

用法

您需要使用 IsMeiliSearchable 特性和实现 MeiliSearchable 接口,而不是 Laravel Scout 的 Searchable 特性。在您的模型中将 Searchable 特性替换为 IsMeiliSearchable 特性。您的模型应该看起来像这样

class Food extends Model implements MeiliSearchable
{
    use IsMeiliSearchable;
    
    /**
     * @var string[] Mass-assignable attributes
     */
    protected $fillable = [
        'name',
    ];
    
    /**
     * Get attributes used for search
     */
    public function toSearchableArray(): array
    {
        return [
            'name' => $this->name,
        ];
    }
}

为了使索引设置的处理比 Laravel Scout 更容易,每个模型都包含其自己的索引设置,用于可搜索、可排序和可筛选属性

class Recipe extends Model implements MeiliSearchable
{
    use IsMeiliSearchable;
    
    /**
     * Define the searchable attributes for the model
     */
    public static function getSearchableAttributes(): array
    {
        return [
            'name',
            'difficulty',
            'ingredient_names',
        ];
    }

    /**
     * Define the search sortable attributes for the model
     */
    public static function getSortableAttributes(): array
    {
        return [
            'name',
            'difficulty',
        ];
    }

    /**
     * Define the search filter attributes for the model
     */
    public static function getFilterableAttributes(): array
    {
        return [
            'difficulty',
        ];
    }
}

默认情况下,所有属性都是可搜索的。如果您想从搜索中省略某些属性,您必须在 getSearchableAttributes() 方法中定义所有剩余的属性。

索引

要为所有模型创建搜索索引、设置它们的索引设置并将所有现有模型导入索引,您可以使用 meili:setup 命令

php artisan meili:setup

如果您想为单个模型单独执行以下步骤之一,您可以使用以下命令

要为单个模型创建搜索索引,您可以使用 meili:create {model} 命令

php artisan meili:create App\\Models\\Food

要同步索引设置,例如可搜索、可排序和可筛选属性,您可以使用 meili:sync-settings {model} 命令

php artisan meili:sync-settings App\Models\Food

要将模型导入搜索索引,您可以使用 meili:import {model} 命令

php artisan meili:import App\Models\Food

测试

composer test

变更日志

请参阅 CHANGELOG 了解最近更改的更多信息。

鸣谢

许可证

MIT 许可证(MIT)。请参阅 许可证文件 获取更多信息。