我将 Scout 与 meilisearch 结合使用,我希望搜索结果包含额外的数据,例如链接 url 或缩略图 url。到目前为止,在文档中我已经找到(并使用)了如何定义索引字段、可过滤字段和可排序字段。但没有找到如何添加任意数据,除了使用
toSearchableArray
函数,如果添加的话确实会添加数据,但它也会索引它,这不是我想要的。一件事是将字段添加到索引,另一件事是仅将它们添加到检索的数据中。
另外,请注意,我想将所有数据打包在服务器端,而不是客户端层。
如何做?嗯,我还必须说我目前只使用 meilisearch-js 做前端,类似(非常精简):
import { MeiliSearch } from 'meilisearch'
const client = new MeiliSearch({
host: 'http://localhost:7700/',
apiKey: 'mykey',
});
function search_seeds(value, options){
seeds.search(value, options).then(response => {
build_search_results_menu(response.hits);
})
}
[...]
我希望搜索结果包含额外的数据,例如链接网址或缩略图网址。
您可以利用 Eloquent:API 资源
php artisan make:resource PostResource
应用程序/Http/Resources/Post.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class Post extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'title' => $this->title,
'description' => $this->description,
'url' => $this->url, // URL of the post
'thumb_url' => $this->thumb_url, // Thumb url of the post
];
}
}
并使用 API 资源作为搜索结果和 JSON 响应之间的转换层。
路线/web.php
<?php
use App\Http\Resources\Post as PostResource;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use \App\Models\Post;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function (Request $request) {
return PostResource::collection(
Post::search($request->search)
->paginate(2)
);
});