chriswillerton / searchable
为 Laravel Eloquent 模型提供的可搜索特征。
1.0.0
2016-07-11 08:06 UTC
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-09-29 04:49:12 UTC
README
为 Laravel Eloquent 模型提供的可搜索特征。
此特征使用全文搜索来搜索单个模型。提供结果集合以帮助按相关性排序多个模型搜索。
安装
将以下内容添加到您项目中的 composer.json
文件中
"chriswillerton/searchable": "1.*"
或者您可以在项目根目录的命令行中运行以下命令
composer require "chriswillerton/searchable" "1.*"
设置
要开始使用,请将特征添加到模型中
use ChrisWillerton\Searchable\Searchable;
class YourModel extends Eloquent
{
use Searchable;
protected $full_text_index = 'title, content';
您还需要定义数据库中设置的全文索引。将此作为名为 $full_text_index
的属性添加到模型中。
用法
您可以使用如下方式使用可搜索特征
$results = YourModel::search('search term')
->orderBy('relevance', 'desc')
->get();
集合用于收集多个模型搜索结果,并使其易于按相关性对整个集合进行排序。假设您有 Article、Post 和 Product 类,但您想要所有这些类的结果混合在一起并按相关性排序。您可以这样做
// Set which models we wish to search
$models_to_search = [
Article::class,
Post::class,
Product::class
];
$term = 'search term';
$model_results = [];
// Loop through each model and perform the search query
foreach ($models_to_search as $model)
{
$model_results[] = $model::search($term)
->get()
->toArray();
}
// Merge each result set together into a single array of results
$merged_results = array_merge(...$model_results);
// Add these results to a collection...
$collection = new ChrisWillerton\Searchable\SearchableResults($merged_results);
// and order them by relevance
$results = $collection->getByRelevance();
但是,您应该考虑上述操作的性能影响。如果需要最大化的性能,最好提出特定的搜索解决方案。