ctf0/easy-searchable

轻松搜索模型与关联属性

资助包维护!
ctf0

v1.1.6 2021-03-03 11:19 UTC

This package is auto-updated.

Last update: 2024-08-30 01:26:53 UTC


README

EasySearchable
Latest Stable Version Total Downloads

安装

composer require ctf0/easy-searchable

设置

还可以查看 https://github.com/laravie/query-filter#search-queries

  • 在您的模型中添加
use ctf0\EasySearchable\Traits\HasSearch;

class Post extends Model
{
    use HasSearch;

    // searched attributes
    //
    // when empty, all model fields will be searched
    // except "dates, primary_key, hidden"
    public $searchableAttributes = [];

    // or have a complete freedom and directly use
    public function getSearchableAttributes()
    {
        return [
            'name->' . app()->getLocale(),
            // ...
        ];
    }

    // ignore attributes
    //
    // so instead of listing all the needed columns in `$searchableAttributes`
    // you can ignore the ones you don't need here
    public $searchableAttributesIgnore = [];

    // searched relations
    //
    // when empty, no relation will be searched
    // * under each relation add the '$searchableAttributes' and we will pick them up automatically
    // * doesn't support nested relations
    public $searchableRelations  = [];

    // we search using the full sentence,
    // however if you prefer to search by words, then use
    public $replaceSpace = true;

    // to force searching dates
    public $searchableDates = true;
}

用法

// auto search in model & relations attributes
Post::search('search for something')->get();

// to strict search even further, wrap the text with either `'` or `"`
Post::search('"search for something"')->get();

// search in specific fields
Post::search('search for something', ['columnName','relation.columnName'])->get();

形态关系搜索

可以使用

// model
public function scopeWorkerSearch($query, $searchTerm)
{
    return $query->orWhereHasMorph(
        'workerable', // name of the morph relation
        '*',
        function ($q) use ($searchTerm) {
            $q->search($searchTerm);
        }
    );
}

// controller
return $query->search($text)->workerSearch($text);

安全

如果您发现任何安全相关的问题,请通过电子邮件联系 ctf0-dev@protonmail.com