玉米科技 / laravel-searchable
Laravel Searchable
4.0.0
2024-03-27 10:46 UTC
Requires
- php: ^8.1
- illuminate/database: ^10.0|^11.0
- illuminate/support: ^10.0|^11.0
- spatie/laravel-package-tools: ^1.14.1
Requires (Dev)
- larastan/larastan: ^2.9
- laravel/pint: ^1.14
- orchestra/testbench: ^8.0|^9.0
- pestphp/pest: ^2.34
- pestphp/pest-plugin-arch: ^2.7
- pestphp/pest-plugin-laravel: ^2.3
- phpstan/extension-installer: ^1.3
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
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
变更日志
请参阅变更日志以获取有关最近更改的更多信息。
贡献
请参阅贡献指南以获取详细信息。
安全漏洞
请审查我们的安全策略,了解如何报告安全漏洞。
鸣谢
许可证
MIT 许可证 (MIT)。请参阅许可证文件以获取更多信息。