97.全文搜索(四)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 97 小节:First Class Search: Instant Results
本节内容
在开始本节内容之前,我们做点小工作。默认情况下,algolia「索引」会从模型的 toArray 方法中读取数据来做持久化。如果要自定义同步到搜索索引的数据,可以重写模型上的 toSearchableArray 方法。我们同步话题模型的path
:
forum\app\Thread.php
.
.
public function toSearchableArray()
{
return $this->toArray() + ['path' => $this->path()];
}
}
同步数据:
$ php artisan scout:import 'App\Thread'
刷新页面:
我们开始本节的内容:实现上一节说到的更进一步的搜索功能。首先我们安装 vue-instantsearch:
$ npm install --save vue-instantsearch
注:如果安装失败请尝试
yarn add vue-instantsearch --no-bin-links
然后我们注册使用:
forum\resources\assets\js\bootstrap.js
window._ = require('lodash');
import InstantSearch from 'vue-instantsearch';
.
.
window.Vue = require('vue');
Vue.use(InstantSearch);
.
.
接着我们注册路由并在页面初步实现搜索功能:
forum\routes\web.php
.
Auth::routes();
Route::view('scan','scan');
.
forum\resources\views\scan.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<ais-index
app-id="{{ config('scout.algolia.id') }}"
api-key="{{ config('scout.algolia.key') }}"
index-name="threads"
>
<ais-search-box></ais-search-box>
<ais-refinement-list attribute-name="channel.name"></ais-refinement-list>
<ais-results>
<template scope=" { result } ">
<p>
<a href="result.path">
<ais-highlight :result="result" attribute-name="title"></ais-highlight>
</a>
</p>
</template>
</ais-results>
</ais-index>
</div>
@endsection
我们访问页面查看效果: