飞猿公司 / 深度搜索
Laravel 的高级模型和关系搜索
v0.3
2018-10-21 16:04 UTC
Requires
- laravel/framework: >=4.2
This package is not auto-updated.
Last update: 2024-09-29 05:41:53 UTC
README
DeepSearch 是一个 Laravel 搜索包,它通过递归方式高效地根据搜索词在模型及其任何给定关系中的出现来查找模型记录。
比如说,你有一个模型 Post,该模型拥有多个评论,而 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 flyingapesinc/deepsearch
之后,将 ServiceProvider 添加到 config/app.php 文件中的 providers 数组中
FlyingApesInc\DeepSearch\ServiceProvider::class,
如果你愿意,可以添加 facade 以便使用
'DeepSearch' => FlyingApesInc\DeepSearch\Facade::class,
如何使用
使用 trait
在你的模型中使用该 trait
use FlyingApesInc\DeepSearch\Traits\DeepSearchable; class Model extends Eloquent { use DeepSearchable; ... }
deepSearch() 方法会返回你的搜索结果。它接受 3 个参数
- $search 要查找的搜索字符串
- $fields 你想要搜索的模型字段数组
- $relationFields 主模型及其要搜索的字段的相关数组
$posts = Post::deepSearch($userInput, ['title'], [ 'comments' => 'comment', 'comments.user' => ['name', 'lastname'] ])->get();
使用静态类
或者,你可以使用静态类 DeepSearch::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'], ] ] ];
链式调用
deepSearch() 和 find() 方法返回一个查询,所以你需要自己通过 get() 或 paginate(n) 获取结果,甚至可以链式调用其他方法。以下是一个示例
$search = DeepSearch::find($userInput, App\Post::query(), $searchSchema)->where('active', 1)->paginate(10);
作者
- lHumanizado
- Rubenazo