定制 baethon/eloquent-searchable-scope 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

baethon/eloquent-searchable-scope

Composer 安装命令:

composer require baethon/eloquent-searchable-scope

包简介

An Eloquent scope for building a search query using LIKE statements

README 文档

README

An Eloquent scope for building a search query using LIKE statements, which also supports searching using relations.

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

Installation

composer require baethon/eloquent-searchable-scope

Model configuration

Import Searchable trait and use it in model:

namespace App\Models;

use Baethon\Laravel\Scopes\Searchable;

class Post extends Model
{
    use Searchable;
}

Trait requires defining the getSearchableOptions() method:

namespace App\Models;

use Baethon\Laravel\Scopes\Searchable;
use Baethon\Laravel\Scopes\SearchableOptions;

class Post extends Model
{
    use Searchable;
    
    public function getSearchableOptions(): SearchableOptions
    {
        return SearchableOptions::defaults()
            ->fields(['topic', 'text', 'user.email'];
    }
}

Note: user.email refers to user relation. It has to be defined in the model.

Available Options

The SearchableOptions provides the ability to customize the search functionality in a few ways:

  • breakToWords() - splits the search term into words and searches against each of them.
  • minTermLength(int $minLength) - rejects any string/word that is shorter than the specified number of characters.
  • fields(array $fields) - specifies the fields to be used in the search.

The SearchableOptions::defaults() is equivalent of:

(new SearchableOptions)->minTermLength(3);

Overloading search options

When using the search() scope, it is possible to define the searchable fields.

$foundPosts = Post::query()
    ->search($search, [
        'title',
    ])
    ->get();

or, pass custom options object:

$foundPosts = Post::query()
    ->search($search, SearchableOptions::defaults()->fields(['title'])
    ->get();

If passing a custom options object, ensure that the searchable fields are defined.

Nothing new here!

The idea for this scope has been previously discussed in various places, such as 🔗 here and 🔗 here. However, since it can be difficult to locate these resources every time one needs them, I have created a package that simplifies the installation process. It is important to note that this package does not introduce any novel concepts.

Testing

composer test

统计信息

  • 总下载量: 1.94k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-02-06

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固