illusi03 / lara-search
为 Laravel 提供高级模型和关系搜索
v1.6.2
2021-10-04 23:08 UTC
Requires
- laravel/framework: >=4.2
README
LaraSearch 是一个 Laravel 搜索包,它使用递归来高效地查找模型记录,通过在搜索和在模型提供的任何关系中的任何单词出现来查找。
假设你有一个模型 Post,模型 Post 有 Many 个评论,模型 Comment 属于一个 User。此外,你的应用程序用户搜索了字符串 "Galactic Empire, and... pizza for steve"。
是的,这很有道理。如果你想在 Post 模型的关系链中的任何部分找到给定的字符串,例如
- 可以找到一个标题为 "The love for pizza" 的帖子。
- 可以找到一个评论说 "Wow that was out of this empire" 的帖子。
- 可以找到一个名为 "Steve" 的用户发表的帖子。嗨,Steve。
安装
在你的 composer.json 中需要此包,并更新 composer 以下载包
composer require illusi03/lara-search
之后,将 ServiceProvider 添加到 config/app.php 中的 providers 数组中
Illusi03\LaraSearch\ServiceProvider::class,
如果你愿意,可以添加方便的 facade
'LaraSearch' => Illusi03\LaraSearchFacade::class,
如何使用
使用特质
在你的模型中使用特质
use Illusi03\LaraSearch\Traits\LaraSearchable; class Model extends Eloquent { use LaraSearchable; ... }
LaraSearch() 方法将返回你的搜索结果。它接受 3 个参数
- $search 要查找的搜索字符串
- $fields 你想要搜索的模型字段数组
- $relationFields 一个关联数组,包含主要模型的关联及其你想要搜索的字段
$posts = Post::laraSearch($userInput, ['title'], [ 'comments' => 'comment', 'comments.user' => ['name', 'lastname'] ])->get();
使用静态类
或者,你可以使用静态类 LaraSearch::find()。它接受 3 个参数
- $search 要查找的搜索字符串
- $model 你想要返回记录的模型。例如:'App\Post'
- $searchSchema 一个包含主要模型要搜索的关联及其字段的数组。格式如下
$searchSchema = [ 'fields' => ['title'], // Fields where you want to search in the main model 'relationships' => [ // Relationships, if any [ 'relationship' => 'comments', // Here you put name of the relationship 'fields' => 'comment', // And here the fields where you want to search in the related table ], [ 'relationship' => 'comments.user', // Use dot notation for inner relations 'fields' => ['name', 'lastname'], ] ] ];
链式调用
LaraSearch() 和 find() 方法返回一个查询,因此你需要自己使用 get() 或 paginate(n) 来获取结果,甚至可以链式调用其他方法。以下示例中我们得到
$search = LaraSearch::find($userInput, App\Models\Post::query(), $searchSchema)->where('active', 1)->paginate(10);
作者
- lHumanizado
- Rubenazo
- Illusi03