liqueurdetoile / cakephp-fuse
CakePHP 3/4 插件,基于 Fuse 实现模糊搜索
Requires
- php: >=7.1
- adbario/php-dot-notation: ^2.2
- cakephp/cakephp: ^3.5|^4
- loilo/fuse: ^3.6
Requires (Dev)
- phpstan/phpstan: ^0.12.55
- phpunit/phpunit: ^8.0
This package is auto-updated.
Last update: 2024-09-24 16:55:49 UTC
README
CakePHP-fuse 插件
此插件是围绕 Fuse 的简单包装行为,用于在模型中实现模糊搜索。搜索只能针对字符串进行。
此行为需要至少 PHP 7.1,并且只能与 CakePHP 3.x 和 4.x 分支一起使用。
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
安装 composer 包的推荐方法是
composer require liqueurdetoile/cakephp-fuse
插件本身只是一个行为,可以在 initialize
方法中将它附加到 initialize
方法中的任何模型上
$this->addBehavior('Lqdt/CakephpFuse.Fuse');
行为也可以在“实时”中附加,因为它不需要任何额外的初始化操作。
使用
基本使用
该行为在模型上提供了一个 fuse
方法,用于获取配置查询。为了方便起见,还提供了一个自定义的查找器。以下两个调用完全等价
$query = $this->Items->fuse('test'); $query = $this->Items->find('fuse' ['filter' => 'test']);
如果没有提供额外的选项或配置,模糊搜索将应用于所有具有默认选项的字符串字段。任何接受 Fuse 的选项都可用。例如,要限制键和调整阈值(假设 Items 数据中有一个 name
字段)
$query = $this->Items->fuse('test', ['keys' => ['name'], 'threshold' => 0.2]); $query = $this->Items->find('fuse' ['filter' => 'test', 'fuse' => [keys' => ['name'], 'threshold' => 0.2]]);
持久配置
您可以将模型设置为始终在使用 fuse 时使用给定的持久配置集。如果也提供了实时选项,则它们将与持久选项混合,并在冲突时覆盖后者。
// In the initialize method of the model $this ->addBehavior('Lqdt/CakephpFuse.Fuse') ->setSearchableFields(['name']) ->setOptions(['threshold' => 0.2]); // or $this ->addBehavior('Lqdt/CakephpFuse.Fuse') ->setOptions([ 'keys' => ['name'], 'threshold' => 0.2 ]); // or $this->addBehavior('Lqdt/CakephpFuse.Fuse', [ 'keys' => ['name'], 'threshold' => 0.2 ]);
嵌套关联
也可以在嵌套关联(仅 hasOne
或 BelongsTo
)中执行搜索,方法是使用点分隔符和 属性名
// Assuming Items belongsTo Owners, with owner as property and name as string field $query = $this->Items->fuse('test', ['keys' => ['name', 'owner.name']])->contain(['Owners']); // Assuming Owners also belongsTo Services, with service as property and name as string field $query = $this->Items->fuse('test', ['keys' => ['name', 'owner.service.name']])->contain(['Owners', 'Owners.Services']);
自动键检测
如果没有在选项中提供键,则模型将考虑每个 string
字段作为可搜索键。这也适用于查询中包含的任何模型
// Will search any string fields in Items, Owners and Services $query = $this->Items->fuse('test')->contain(['Owners', 'Owners.Services']);
API 技巧表
fuse(string $finder, array $options = [], \Cake\ORM\Query $query = null) : Query
使用 finder
关键字(s)在查询的结果上安排模糊搜索,并返回查询。如果没有提供,则仅在运行时应用自动键和默认选项
find('fuse', array $options = [])
方便的依赖查找器,依赖于 fuse
方法。为了避免常规查询选项和 fuse 选项之间的任何冲突,预期选项必须遵循以下约定:['filter' => <filter>, 'fuse' => [<fuseOption>:<value>, ...]]
getSearchableFields(): array
返回持久定义的模糊搜索键,或者在没有设置时使用自动字段填充它们
setSearchableFields(array $fields = []): self
设置持久定义的模糊搜索键
getFuseOptions(): array
返回当前持久选项
setFuseOptions(array $options, bool $replace = false): self
设置持久选项。如果键冲突,提供的值将覆盖当前值。如果 replace
设置为 true,则替换所有选项
行为代码中还有一些更高级的工具。
变更日志
- v1.0.2 : 修复
find('fuse')
文档 - v1.0.1: 添加对 cakePHP ^4.2 的兼容性(
getTable
弃用) - v1.0.0: 首次发布