fynduck/laravel-searchable

laravel-searchable 的描述。

2.2 2020-12-09 11:16 UTC

This package is auto-updated.

Last update: 2024-09-09 19:21:57 UTC


README

Software License Latest Version on Packagist Total Downloads

安装

composer require fynduck/laravel-searchable

用法

use Fynduck\LaravelSearchable\src\Searchable;

class User extends \Eloquent
{
    use Searchable;

     /**
     * Searchable rules.
     * Columns and their priority in search results.
     * Columns with higher values are more important.
     * Columns with equal values have equal importance.
     * @var array
     * @return array
     */
    protected function toSearchableArray()
    {
        return [
            'columns' => [
                'name'  => 10,
                'email' => 5,
            ],
             'joins' => [
                 'posts' => ['users.id','posts.user_id'],
             ],
        ];
    }

    /**
     * Select fields
     * @return array
     */
    public function selectFields()
    {
        return [
            'users.name',
            'users.email'
        ];
    }
    
    public function posts()
    {
        return $this->hasMany('Post');
    }

}

现在您可以搜索您的模型。

// Simple search
$users = User::search($query)->get();

// Search and get relations
// It will not get the relations if you don't do this
$users = User::search($query)
            ->with('posts')
            ->get();

分页搜索

与 Laravel 默认查询一样简单

// Search with relations and paginate
$users = User::search($query)
            ->with('posts')
            ->paginate(20);

混合查询

搜索方法是与任何 Eloquent 方法兼容的。您可以执行如下操作

// Search only active users
$users = User::where('status', 'active')
            ->search($query)
            ->paginate(20);

自定义阈值

默认的接受相关性阈值是所有属性相关性的总和除以 4。要更改此值,您可以在 search() 中传递第二个参数,如下所示

// Search with lower relevance threshold
$users = User::where('status', 'active')
            ->search($query, 0)
            ->paginate(20);

上面的代码将按相关性顺序返回所有用户。

全文搜索

默认情况下,多词搜索项被分割,Searchable 逐个搜索每个词。相关性在优先考虑匹配多个词的匹配项中发挥作用。如果您想优先考虑包含多词搜索(因此,不分割成单词)的匹配项,可以通过将第三个值设置为 true 来启用全文搜索。示例

// Prioritize matches containing "John Doe" above matches containing only "John" or "Doe".
$users = User::search("John Doe", null, true)->get();

如果您明确只想搜索全文匹配,可以通过将第四个参数设置为 true 来禁用多词分割。

// Do not include matches that only matched "John" OR "Doe".
$users = User::search("John Doe", null, true, true)->get();

贡献

有关详细信息,请参阅 CONTRIBUTING

安全

如果您发现任何与安全相关的问题,请通过 DummyAuthorEmail 邮件发送,而不是使用问题跟踪器。

许可协议

MIT 许可协议 (MIT)。有关更多信息,请参阅 许可文件