Laravel 中的全文搜索
Laravel 通过 whereFullText
和 orWhereFullText
方法,提供了健壮的全文搜索能力,提供了一种相较于 LIKE 语句更复杂的数据查询方法。
技术要求
- 支持的数据库:MariaDB、MySQL 或 PostgreSQL
- 目标字段全文(Full-text)索引
- 对于大数据量系统,请考虑使用 ElasticSearch 或 Meilisearch 替代
whereFullText
方法直接与数据库的全文搜索功能集成。以下是一个基本实现:
use Illuminate\Support\Facades\DB;
$users = DB::table('users')
->whereFullText('bio', 'web developer')
->get();
基于此,你可以为博客或 CMS 建立更复杂的功能。下例演示了跨多字段搜索同时保留了按 category 过滤的能力:
// ArticleController.php2
public function search(Request $request)
{
return Article::query()
->whereFullText(['title', 'content'], $request->search)
->when($request->category, function ($query, $category) {
$query->where('category', $category);
})
->orderBy('published_at', 'desc')
->paginate(15);
}
// migration
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->string('category');
$table->timestamp('published_at');
$table->fullText(['title', 'content']);
});
Laravel 会自动为数据库系统生成适当的 SQL 语法。对于 MariaDB 和 MySQL,默认情况下,它在自然语言模式下使用 MATCH AGAINST 语句构造查询。
这种方法简化了复杂的搜索实现,同时为中等规模的应用保持了高效的查询性能。对于需要高级搜索功能或处理大量数据的系统,可以考虑使用 ElasticSearch 或 Meilisearch 等专用搜索服务。