WinterCMS开发之数据查询(搜索功能)
WinterCMS的搜索功能可以借助一个非常好用的插件 - siteSearch,在后台插件安装的地方直接搜索关键词即可,而且是免费的,使用它可以很快进行相关内容的搜索。
安装完成后先配置相关参数,常用的Blog和CMS Pages根据需要打开即可

搜索功能的实现
构建搜索框表单
#option1 手动设置
只需要在模板的layout或者header这样的公共区域准备搜索框,按照下面格式来
<form action="{{ 'search' | page }}" method="get">
<input name="q" type="text" placeholder="What are you looking for?" autocomplete="off">
<button type="submit">Search</button>
</form>#option2 component自动生成
除此以外你也可以通过component库来拖入生成该表单,该插件提供了三个component,将其中的Search input拖入模板即可

搜索结果展现
创建用于搜索结果显示的page,并拖入Search results component

Tips:如果我们不需要使用组件生成出的html可以把comonent所在目录的htm模板文件中的代码复制出来也是一样的。
这时候我们发现前端已经可以正常搜索数据了,但是最后依旧有一个很重要的问题没有解决,就是自建的Plugin中的数据是无法搜索的。
Plugin数据的搜索
找到Plugin所属目录下的Plugin.php文件并添加以下代码,注意修改其中的model、查询条件及字段参数。
public function boot()
{
\Event::listen('offline.sitesearch.query', function ($query) {
// The controller is used to generate page URLs.
$controller = \Cms\Classes\Controller::getController() ?? new \Cms\Classes\Controller();
// Search your plugin's contents
$items = Models\Book
::where('title', 'like', "%${query}%")
->orWhere('short_description', 'like', "%${query}%")
->get();
// Now build a results array
$results = $items->map(function ($item) use ($query, $controller) {
// If the query is found in the title, set a relevance of 2
$relevance = mb_stripos($item->title, $query) !== false ? 2 : 1;
// Optional: Add an age penalty to older results. This makes sure that
// newer results are listed first.
// if ($relevance > 1 && $item->created_at) {
// $ageInDays = $item->created_at->diffInDays(\Illuminate\Support\Carbon::now());
// $relevance -= \OFFLINE\SiteSearch\Classes\Providers\ResultsProvider::agePenaltyForDays($ageInDays);
// }
return [
'title' => $item->title,
'text' => $item->short_description,
'url' => $controller->pageUrl('book', ['slug' => $item->slug]),
'thumb' => optional($item->poster)->first(), // Instance of System\Models\File
'relevance' => $relevance, // higher relevance results in a higher
// position in the results listing
// 'meta' => 'data', // optional, any other information you want
// to associate with this result
// 'model' => $item, // optional, pass along the original model
];
});
return [
'provider' => 'Book', // The badge to display for this result
'results' => $results,
];
});
}