nebkam / odm-search-param
6.0.5
2023-08-08 14:29 UTC
Requires
- php: ^8.2
- ext-mongodb: ^1.15
- doctrine/mongodb-odm: ^2.5
Requires (Dev)
- phpunit/phpunit: ^10.0
README
原因
- 如果你使用 Doctrine MongoDB ODM
- 你需要一些 搜索 功能,这些功能可以通过 Aggregation Builder 的
QueryBuilder
或MatchPhase
来实现 - 你有一个包含搜索参数的类(例如,在 Symfony 中的域类)
- 你不想手动将搜索参数映射到构建语句
用法
- 搜索过滤器类可以是任何具有 公共 属性的类
- 属性应该使用
#[SearchParam]
属性标记 - 使用
SearchParamParser::parse
与QueryBuilder|MatchStage
实例来构建查询
示例
逐字(String
和 Bool
类型)
class SearchFilter { #[SearchParam(type: SearchParamType::String)] public string $name; }
构建查询为
$builder->field('name')->equals($propertyValue);
使用不同的属性名称
class SearchFilter { #[SearchParam(type: SearchParamType::Exists, field: 'images')] public bool $hasImages; }
构建查询为
$builder->field('images')->exists(true);
类型转换(Int
类型)
class SearchFilter { #[SearchParam(type: SearchParamType::Int)] public $age; }
构建查询为
$builder->field('age')->equals((int) $propertyValue);
使用数组进行类型转换(《IntArray》和《StringArray》类型)
class SearchFilter { /** * @var int[] */ #[SearchParam(type: SearchParamType::IntArray)] public array $grades; }
构建查询为
$builder->field('grades')->in($propertyValuesAllCastedToInt);
使用枚举的备用值(《StringEnum》和《IntEnum》类型)
class SearchFilter { #[SearchParam(type: SearchParamType::StringEnum)] public SideOfTheWorldEnum $sideOfTheWorld; }
构建查询为
$builder->field('sideOfTheWorld')->equals($propertyValue->value);
使用枚举数组的备用值(《StringEnumArray》和《IntEnumArray》类型)
class SearchFilter { /** * @var SideOfTheWorldEnum[] */ #[SearchParam(type: SearchParamType::StringEnumArray)] public array $sidesOfTheWorld; }
构建查询为
$builder->field('sideOfTheWorld')->in($backingValuesOfPropertyValue);
通过范围查询(《RangeInt》和《RangeFloat》类型)
class SearchFilter { #[SearchParam(type: SearchParamType::RangeInt, direction: SearchParamDirection::From)] public int $price; }
构建查询为
$builder->field('price')->gte((int) $propertyValue);
通过指定可调用来自定义查询构建
class SearchFilter { #[SearchParam(type: SearchParamType::Callable, callable: [SomeClass::class, 'setStatus'])] public string $status; } class SomeClass { public static function setStatus(Builder|MatchStage $builder, $value, $filter) { // Call $builder methods to build the query } }