black-lamp / yii2-search
Active Record模型搜索组件
2.0.2
2017-05-10 08:33 UTC
Requires
- yiisoft/yii2: ^2.0.4
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-14 19:20:15 UTC
README
安装
运行命令
composer require black-lamp/yii2-search
或者添加
"black-lamp/yii2-search": "^2.0.0"
到你的composer.json的require部分。
将'SiteSearch'组件添加到应用配置中
'components' => [ // ... 'search' => [ 'class' => bl\search\SearchComponent::class, // models where you need the search 'models' => [ 'article' => [ 'class' => frontend\models\Article::class, 'label' => 'Articles' ], // ... ] ], ]
在模型数组中添加你想要进行搜索的Active Record模型。
class
是模型的名称。
label
是在视图中显示的标题。
在需要搜索的模型中实现接口
/** * @property integer $id * @property string $title * @property string $shortText * @property string $fullText * @property string $socialNetworksText */ class Article extends ActiveRecord implements \bl\search\interfaces\SearchInterface { // ... /** * @inheritdoc */ public function getSearchTitle() { return $this->title; } /** * @inheritdoc */ public function getSearchDescription() { return $this->shortText; } /** * @inheritdoc */ public function getSearchUrl() { return Url::toRoute["/articles/$this->id"]; } /** * @inheritdoc */ public function getSearchFields() { return [ 'title', 'shortText', 'fullText' ]; } }
使用
调用方法获取搜索结果。此方法返回一个包含SearchResult对象的数组。
/** * @var \bl\search\data\SearchResult[] $result */ $result = Yii::$app->searcher->search('Black lamp'); foreach($result as $res) { $res->title; $res->description; $res->url; }