postgresql - 使用 Postgresql 的 ApiPlatform Regex 属性过滤器
问题描述
我正在尝试向我的 ApiPlatform 项目中的实体添加自定义过滤器,该过滤器允许我过滤给定正则表达式模式的特定属性。
根据 ApiPlatform 文档,我提出了以下类(这是他们示例的近似副本,只有 where 子句不同):
<?php
namespace App\Filter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;
final class RegexFilter extends AbstractContextAwareFilter
{
protected function filterProperty(
string $property,
$value,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
string $operationName = null
) {
// otherwise filter is applied to order and page as well
if (
!$this->isPropertyEnabled($property, $resourceClass) ||
!$this->isPropertyMapped($property, $resourceClass)
) {
return;
}
$parameterName = $queryNameGenerator->generateParameterName($property); // Generate a unique parameter name to avoid collisions with other filters
$queryBuilder
->andWhere(sprintf('(o.%s ~ :%s) = true', $property, $parameterName))
->setParameter($parameterName, $value);
}
// This function is only used to hook in documentation generators (supported by Swagger and Hydra)
public function getDescription(string $resourceClass): array
{
if (!$this->properties) {
return [];
}
$description = [];
foreach ($this->properties as $property => $strategy) {
$description["regexp_$property"] = [
'property' => $property,
'type' => 'string',
'required' => false,
'swagger' => [
'description' => 'Filter using a regex. This will appear in the Swagger documentation!',
'name' => 'Custom name to use in the Swagger documentation',
'type' => 'Will appear below the name in the Swagger documentation',
],
];
}
return $description;
}
}
当我运行我的代码时,这会产生以下 DQL:
SELECT o FROM App\Entity\Vehicle o WHERE (o.licensePlate ~ :licensePlate_p1) = true ORDER BY o.id ASC
但是我无法让 Lexer 理解波浪号 ~ 字符:
Doctrine\ORM\Query\QueryException
[Syntax Error] line 0, col 56: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '~'
我怎样才能让 Doctrine 理解波浪号?
解决方案
原来我已经很接近了,simPod 的回答帮助我填补了空白。
- 我复制了他的自定义 DQL 函数并将其添加到我的 Doctrine yaml 配置中
在我的
RegexFilter
我不得不稍微修改 where 子句:->andWhere(sprintf('REGEX(o.%s, :%s) = true', $property, $parameterName))
推荐阅读
- php - 如何使存储的图像文件夹只能通过 php 代码访问
- pytorch - 自定义数据集 os.path.join() 返回类型错误
- python - 如何在python的两侧迭代函数?
- javascript - graphql中的400个错误请求
- android - 改造获得单弦最佳实践
- mysql - 多对多表还是一张表?
- javascript - 使用javascript计算时总和为零
- javascript - 无法使用 window.scrollTo 滚动到页面末尾
- android - Android导航组件在使用安全参数时将包作为参数传递
- google-apps-script - 需要帮助,导出的 PDF 中未刷新电子表格公式