匹配两个字段的自定义过滤器



我只想要一个API端点匹配两个字段,registrationIdhash

我在网上找不到任何这样的例子,我只能单个匹配,正则表达式匹配,或子句等。任何地方都没有这样的例子,只是查询数据库以返回匹配两列的行。

我有一个名为registrationhashes的表。在实体中,我添加了这一行:

#[ApiFilter(RegistrationSearchFilter::class, properties: ['registrationId', 'hash'])]

然后我已经写了一个自定义过滤器:

final class RegistrationSearchFilter extends AbstractFilter
{
protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
{
if ($property !== 'search') {
return;
}
$alias = $queryBuilder->getRootAliases()[0];
$queryBuilder->andWhere(sprintf('%s.registrationId = :search AND %s.hash = :hash', $alias, $alias));
}
public function getDescription(string $resourceClass): array
{
if (!$this->properties) {
return [];
}
$description = [];
foreach ($this->properties as $property => $strategy) {
$description["regexp_$property"] = [
'property' => $property,
'type' => Type::BUILTIN_TYPE_STRING,
'required' => false,
'description' => 'Filter using a regex. This will appear in the OpenApi documentation!',
'openapi' => [
'example' => 'Custom example that will be in the documentation and be the default value of the sandbox',
'allowReserved' => false,// if true, query parameters will be not percent-encoded
'allowEmptyValue' => true,
'explode' => false, // to be true, the type must be Type::BUILTIN_TYPE_ARRAY, ?product=blue,green will be ?product=blue&product=green
],
];
}
return $description;
}
}

我只是把描述函数放在那里,现在从其他地方复制。

但是正如您从WHERE子句中看到的,我需要匹配registrationId和hash,但是我只有一个值可以匹配。

我怎样才能做到这一点?

查看搜索过滤器文档,您将看到一个组合两个搜索过滤器的示例。我相信这可以完成您的任务,而不需要自定义过滤器。

use ApiPlatformDoctrineOrmFilterSearchFilter;
#[ApiResource]
#[ApiFilter(SearchFilter::class, properties: ['registrationId' => 'exact', 'hash' => 'exact'])]
class RegistrationHash
{
// ...
}

http://localhost:8000/api/registrationhashes?registrationId=10&hash=3C76B43F

最新更新