theupriser / laravel-searchable
Laravel Searchable
4.0
2024-03-17 13:45 UTC
Requires
- php: ^8.0
- illuminate/database: ^9.0|^10.0|^11.0
- illuminate/support: ^9.0|^10.0|^11.0
- spatie/laravel-package-tools: ^1.14.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.4
- orchestra/testbench: ^7.0|^8.0
- phpunit/phpunit: ^9.5|10.0
- vimeo/psalm: ^4.20
README
Laravel Searchable 🔍
通过模型属性和关系轻松添加带权重的搜索。
该包目前支持 MySQL 和 PostgreSQL。
安装
您可以通过 composer 安装此包
composer require maize-tech/laravel-searchable
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="Maize\Searchable\SearchableServiceProvider" --tag="searchable-config"
这是已发布配置文件的内容
return [ /* |-------------------------------------------------------------------------- | Default match weight |-------------------------------------------------------------------------- | | The weight of all searched words which match at least one of the | list of searchable attributes. | Defaults to 1. | */ 'default_match_weight' => 1, ];
用法
要使用此包,请将 Maize\Searchable\HasSearch 特性添加到您想要使其可搜索的每个模型中。
完成后,您可以通过返回您想要搜索的属性(或关系的属性)列表来实现 getSearchableAttributes 抽象方法。
您还可以定义每个可搜索属性的权重。如果没有指定权重,则将从 config/searchable.php 中获取 default_match_weight。
以下是一个包含 HasSearch 特性的示例模型
<?php namespace App\Models; use Maize\Searchable\HasSearch; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Support\Facades\DB; class Article extends Model { use HasSearch; protected $fillable = [ 'id', 'title', 'body', 'creator_name', 'creator_surname', ]; protected $casts = [ 'body' => 'array', ]; /** * Get the model's searchable attributes. * * @return array */ public function getSearchableAttributes(): array { return [ 'title' => 5, // Model attribute 'body.en' => 2, // Single json key of a model attribute 'tags.name', // Relationship attribute 'tags.description.*', // All json keys of a relationship attribute DB::raw("CONCAT(creator_name, ' ', creator_surname)"), // Raw expressions are supported too ]; } /** * Allows fetching the tags bound to current article instance * * @return BelongsToMany */ public function tags(): BelongsToMany { return $this->belongsToMany(Tag::class)->withTimestamps(); } }
现在,您可以使用 scopeSearch 范围方法搜索给定术语
use App\Models\Article; $searchTerm = 'the search string'; Article::query() ->search($searchTerm) ->where('column', '=', 'something') ->get();
就是这样!
该包为每个搜索词和每个可搜索字段生成一个带有 'or' 条件的 SQL 查询。给定的查询返回匹配搜索词的所有模型。此外,搜索结果是有权重的,这意味着查询将按最匹配的模型排序。
如果您不想按匹配权重排序搜索结果,可以将 orderByWeight 标志设置为 false
use App\Models\Article; $searchTerm = 'the search string'; Article::query() ->search($searchTerm, false) ->where('column', '=', 'something') ->get();
测试
composer test
变更日志
有关最近更改的更多信息,请参阅 CHANGELOG
贡献
有关详细信息,请参阅 CONTRIBUTING
安全漏洞
有关如何报告安全漏洞的详细信息,请参阅 我们的安全策略
鸣谢
许可证
MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件