fab2s / searchable
基于全文索引的 Laravel searchable 模型
Requires
- php: ^8.0
- fab2s/strings: ^1.0
Requires (Dev)
- ext-pdo: *
- friendsofphp/php-cs-fixer: ^3.0
- orchestra/testbench: ^7.0
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-08-30 01:51:33 UTC
README
基于 MySQL 全文索引的 Laravel searchable 模型。
本包不追求智能,遵循 KISS 原则。它将允许您通过将模型中的任意字段连接到一个新的列,并使用 MySQL 全文索引来对其进行索引,使任何字段可搜索。
需要 mysql / mariadb 和 Laravel 9.x
安装
使用 composer 安装 Searchable
composer require "fab2s/searchable"
用法
要在特定 model
上使用 Searchable
,只需使用 Searchable
trait 并设置 $searchables
class MyModel extends Model { use Searchable; /** * @var string[] */ protected $searchables = [ 'field1', 'field2', // ... 'fieldN', ]; }
默认情况下,field1
到 fieldN
将被连接并存储到由 Enable
命令添加到模型的默认 SearchQuery::SEARCHABLE_FIELD
字段中。
默认情况下,此可搜索字段的数据类型为 VARCHAR(255)
,但您可以通过覆盖模型中的 Searchable
trait 方法来自定义任何支持全文索引的数据类型和长度。
/** * @return string */ public function getSearchableField(): string { return SearchQuery::SEARCHABLE_FIELD; // searchable } /** * @return string any migration method such as string, text etc ... */ public function getSearchableFieldDbType(): string { return 'string'; } /** * @return int */ public function getSearchableFieldDbSize(): int { return 255; }
您还可以通过覆盖来自定义连接方式
/** * @param string $additional for case where this method is overridden in users * * @return string */ public function getSearchableContent(string $additional = ''): string { return TermParser::prepareSearchable(array_map(function ($field) { return $this->$field; }, $this->getSearchables()), $additional); }
可以通过 $additional
参数使用预处理模型数据,这在加密/解密或匿名化等情况下很有用
/** * @return string */ public function getSearchableContent(): string { $additional = [ $this->decrypt('additional_field1'), 0 . substr((string) $this->decrypt('phone'), 3, 6), // will allow for partial matches ]; return $this->getSearchableContentTrait(implode(' ', $additional)); }
配置好模型后,您可以使用 Enable
命令将 searchable
字段添加到模型中,并对它们进行索引
$ php artisan searchable:enable --help Description: Enable searchable for your models Usage: searchable:enable [options] Options: --root[=ROOT] The place where to start looking for models, defaults to Laravel's app/Models --index To also index / re index -h, --help Display help for the given command. When no command is given display help for the list command -q, --quiet Do not output any message -V, --version Display this application version --ansi|--no-ansi Force (or disable --no-ansi) ANSI output -n, --no-interaction Do not ask any interactive question --env[=ENV] The environment the command should run under -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
停用词
Searchable
包含英文和法语的停用词文件,您可以使用这些文件通过忽略这些文件中列出的单词来减少全文索引。
可以使用 StopWords
命令将这些单词填充到 stopwords
表中
php artisan searchable:stopwords
必须按照 innodb_full_text.cnf 中的示例配置数据库服务器,这些单词才能有效地从索引中排除。
贡献
欢迎贡献,请随时提出问题和提交 pull request。
许可证
Searchable
是开源软件,许可协议为 MIT 许可证。