pascalvgemert/laravel-simple-search

为Laravel eloquent模型提供的一个简单的搜索特性,支持根据相关性评分排序。

0.1.0 2019-08-30 17:19 UTC

This package is auto-updated.

Last update: 2024-08-29 04:55:00 UTC


README

为Laravel eloquent模型提供的一个简单的搜索特性,支持根据相关性评分排序。

需要Laravel 5.5或更高版本!

关于这个包

此特性允许你无需使用Elastic Search数据库或全文搜索表即可对任何表进行搜索。查询包含一些简单的where方法,并支持根据搜索相关性对查询结果进行排序。

安装

你可以使用composer来安装这个包

composer require pascalvgemert/laravel-simple-search

用法

SimpleSearch 特性只能用于Eloquent模型。

class Post extends \Illuminate\Database\Eloquent\Model
{
    use SimpleSearch/SimpleSearch;

    /**
     * Specifiy the columns to search on, and add a weight score if needed.
     * Default weight: 1
     *
     * @var array
     */
    protected $searchable = [
        'title:3',
        'content',
    ];
}

搜索方法

之后,你可以在Eloquent模型实例上使用 search 方法,例如

// Find's posts with the phrases `cats` and/or `funny`.
$results = Post::search('funny cats')->sortByDesc('score')->take(10)->get();

你也可以指定搜索结果必须匹配 所有 关键字或 任意 关键字。

// Find's posts which both include the phrases `cats` and `funny`.
$results = Post::search('funny cats', true)->sortByDesc('score')->take(10)->get();

如果你不想使用相关性评分进行排序,可以指定从结果中移除评分列。

// Find's the last 10 posts with the phrases `cats` and/or `funny`.
$results = Post::search('funny cats', false, true)->sortByDesc('created_at')->take(10)->get();

作者