denismitr/search

该包已被废弃,不再维护。没有推荐替代包。

Laravel 搜索引擎

1.2.2 2016-06-25 15:26 UTC

This package is auto-updated.

Last update: 2020-01-22 22:34:43 UTC


README

#Laravel 搜索引擎

可能有点夸张,因为我只是为正在构建的一个项目构建了这个库。然而它运作得很好,所以我决定发布它。

##安装

composer require denismitr/search

##使用方法

$records = Search::query('some query string or strings go here')
                ->withSearchers([
                    TitleSearcher::class,
                    DescriptionSearcher::class,
                    SomeRelationalSearcher::class
                ])->get();

现在这里是难点:有两个 抽象 搜索器类 SimpleSearcherRelationalSearcher,可以从中继承所有搜索器类和一个公共接口 Searchable 来实现。当然,SimpleSearcher 是用于简单的 Eloquent 模型搜索,而 RelationalSearcher 是用于涉及 关系 的情况。

<?php

namespace App\Queries;

use App\Post;
use Denismitr\Search\Searchable;
use Denismitr\Search\Searchers\SimpleSearcher;

class TitleSearcher extends SimpleSearcher implements Searchable
{
    //Here you specify a Eloquent model class which you search and the collection of which you whant to get
    //as a return of the search
    protected $model = Post::class;

    //Here you specify the field you in which to search
    protected $searchField = 'title';
}

还有另一个更复杂的 RelationalSearcher 用于搜索父模型,例如像这样搜索帖子的主题

<?php

namespace App\Queries;

use App\Post;
use App\Topic;
use Denismitr\Search\Searchable;
use Denismitr\Search\Searchers\RelationalSearcher;

class TopicNameSearcher extends RelationalSearcher implements Searchable
{
    protected $model = Post::class;
    protected $searchField = 'name';

    //Here you specify the Eloquent relational methods (that return hasMany or belongstoMany)
    protected $relation = 'topics';
}

然后你把所有这些放入 Search 类的 withSearchers 方法中,就可以开始使用了。

##注意 每个 Search 实例在 get() 上返回一个单一 Eloquent 模型的集合,过滤掉所有重复项。如果您需要为整个不同且不相关的表输出结果,您需要多个 Search 实例和更多的搜索器集。我知道这有点繁琐。如果我有更多时间,我会将其变成更方便的东西。 另外,如果您此时需要分页,您必须手动完成。使用 Laravel 很简单。