baethon / eloquent-searchable-scope
使用 LIKE 语句构建搜索查询的 Eloquent scope
v2.0.1
2023-08-16 14:37 UTC
Requires
- php: ^8.1
Requires (Dev)
- orchestra/testbench: ^7.0|^8.5
- phpunit/phpunit: ^9.0|^10.1
README
使用 LIKE 语句构建搜索查询的 Eloquent scope,同时也支持使用关系进行搜索。
$foundPosts = Post::query() ->search($search) ->get();
安装
composer require baethon/eloquent-searchable-scope
模型配置
导入 Searchable
特性并在模型中使用它
namespace App\Models; use Baethon\Laravel\Scopes\Searchable; class Post extends Model { use Searchable; }
特性需要定义 getSearchableOptions()
方法
namespace App\Models; use Baethon\Laravel\Scopes\Searchable; use Baethon\Laravel\Scopes\SearchableOptions; class Post extends Model { use Searchable; public function getSearchableOptions(): SearchableOptions { return SearchableOptions::defaults() ->fields(['topic', 'text', 'user.email']; } }
注意:user.email
指的是 user
关系。它必须在模型中定义。
可用选项
SearchableOptions
提供了以几种方式自定义搜索功能的能力
breakToWords()
- 将搜索词拆分成单词并对每个单词进行搜索。minTermLength(int $minLength)
- 拒绝任何短于指定字符数的字符串/单词。fields(array $fields)
- 指定用于搜索的字段。
SearchableOptions::defaults()
等同于
(new SearchableOptions)->minTermLength(3);
覆盖搜索选项
当使用 search()
scope 时,可以定义可搜索的字段。
$foundPosts = Post::query() ->search($search, [ 'title', ]) ->get();
或,传递自定义选项对象
$foundPosts = Post::query() ->search($search, SearchableOptions::defaults()->fields(['title']) ->get();
如果传递自定义选项对象,请确保已定义可搜索字段。
这里没有新内容!
这个 scope 的想法之前在各种地方讨论过,比如 🔗 这里 和 🔗 这里。然而,由于每次需要这些资源时都很难找到它们,我创建了一个简化安装过程的包。需要注意的是,这个包不引入任何新的概念。
测试
composer test