faithfm/smart-search-php

使用简单的Google风格搜索字符串进行复杂过滤操作。

2.4.1 2023-10-30 00:01 UTC

This package is auto-updated.

Last update: 2024-09-30 01:46:41 UTC


README

简单的(但强大的)PHP搜索/过滤,在多个上下文中提供统一的搜索结果

  • MySQL/其他数据库(例如:“where”子句构建器)
  • PHP数组
  • Laravel 集合
  • Laravel 模型
  • Laravel Nova 资源

简单的Google风格搜索字符串可以执行跨多个字段的复杂过滤操作。

(PHP后端等效于 miking/smart-search-filter JavaScript 库)

截图

smart-search-01.jpg

安装

在项目的 composer.json 中要求此包。

composer require faithfm/smart-search-php

注意:对于 Laravel 模型和 Nova 资源,必须手动安装附加依赖项。(适用于 Laravel <= 8.x)

使用示例

首先使用 搜索字符串 和一组 默认搜索字段 创建一个 SmartSearch 实例

use FaithFM\SmartSearch\SmartSearch;

$search = 'optus 320 location:stock -F2701';
$smartSearch = new SmartSearch($search, 'asset_id|location|type|make|model|identifier');

现在可以使用解析后的搜索字符串在单个或多个上下文中执行过滤操作

$filtered = $smartSearch->filterArray($items));
$filteredCollection = $smartSearch->filterCollection($myCollection));
$whereClause = $smartSearch->getSqlFilter());
$data = DB::table('my_table')::where($smartSearch->getBuilderFilter())->get();
// OR
$data = MyModel::where( $smartSearch->getBuilderFilter() )->get();
MyModel::smartSearch('joe', 'location|type')->get();
class MyResource extends Resource
{
    use SmartSearchableNovaResource;
    ...

搜索语法

相关的 miking/smart-search-filter JavaScript 库包括如何使用简单的Google风格搜索语法在多个字段上执行复杂过滤操作的文档

注意:这两个库结合使用为现代Web应用程序的前端/后端过滤提供了一种简单、统一且强大的方法。

调试信息

在解析搜索字符串时,会创建一个“过滤操作”数组。
getFilterOpsDescription() 函数提供了一个人类可读的表示,显示了搜索字符串的解析意图,并提供了解析错误

var_dump($smartSearch->errors);
var_dump($smartSearch->getFilterOpsDescription());

高级选项

上述示例演示了只向 SmartSearch 构造函数提供了两个参数的简单情况,但是还有许多其他高级选项可用。

new SmartSearch($searchString, $defaultFields = "", $allowedFields = "", $options = [], Closure $sqlEscapeStringFn = null)

备注

  • 如果没有明确指定,$allowedFields$defaultFields 相同。

  • 字段列表可以以许多不同的方式指定

$defaultFields = 'location,type';       // comma-separated
$defaultFields = 'location, type';      // comma-separated (with spaces)
$defaultFields = 'location|type';       // pipe-separated
$defaultFields = ['location', 'type'];  // array format
//... and pretty much anything else that can be cast to an array (of strings)
  • $options 参数接受关联数组或 StdClass 对象,并允许定义诸如大小写敏感性和 SQL 通配字符等选项。默认选项是
const DEFAULT_OPTIONS = [
    'caseSensitive' => false,
    'sqlWildcard' => '%',
    'sqlWildcardSingleChar' => '_',
];

注意:所有过滤器目前都不区分大小写。《caseSensitive》选项目前不起作用。

  • 可以在构造函数中指定《$sqlEscapeStringFn》,而不是稍后调用《setSqlEscapeStringFn()`》。