zesty-bus/laravel-simple-search

对 eloquent 模型进行简单的通配符搜索。

2.0.1 2022-05-16 09:29 UTC

This package is auto-updated.

Last update: 2024-09-16 14:41:17 UTC


README

对 eloquent 模型进行简单的通配符搜索。

安装

通过 Composer

composer require zesty-bus/laravel-simple-search

用法

准备你的模型

添加一个可搜索属性。这些是你要搜索的表列。如果模型有关系,你可以使用点表示法来确定路径。

namespace App\Models;

class Post extends Model
{
    protected $searchable = [
        'name', 'body', 'category.name'
    ];
    
    public function category()
    {
        return $this->hasOne(Category::class);
    }
}

搜索

要运行搜索,请在查询上使用 search() 方法。

$posts = Post::search($request->query)->get();

你可以通过传递一个数组来覆盖默认搜索列。

$posts = Post::search($request->query, ['name'])->get();

配置

你可能想要更改模型上的搜索方法名称或搜索属性名称。首先,发布配置。

php artisan vendor:publish --provider="ZestyBus\LaravelSimpleSearch\LaravelSimpleSearchServiceProvider" --tag="config"

只需将方法名称或属性名称更改为符合你要求的内容。

return [

    /**
     *  Name of the eloquent builder method.
     */
    'method' => 'filter',

    /**
     *  Name of the models public searchable property.
     */
    'property' => 'filterable'
];
$posts = Post::filter($request->query, ['name'])->get();
namespace App\Models;

class Post extends Model
{
    protected $filterable = [
        'name', 'body', 'category.name'
    ];
    
    public function category()
    {
        return $this->hasOne(Category::class);
    }
}

许可证

许可证。有关更多信息,请参阅 许可证文件