问题描述
id,name,...,startDate,endDate
public function getStatus() {
if (new \DateTime() < $this->getStartDate()) {
return 'planned';
}
if (new \DateTime() > $this->getEndDate()) {
return 'expired';
}
return 'published';
}
我想做的是能够在此字段上创建过滤器。我似乎无法在文档中找到它。我已经尝试以与在其他字段上创建过滤器相同的方式在其上创建过滤器,但是它没有出现在我的 swagger UI 界面中。
// config/services.yaml
services:
...
view.search_filter:
parent: 'api_platform.doctrine.orm.search_filter'
arguments:
$properties:
id: 'exact'
name: 'ipartial'
...
status: 'exact' // doesn't seem to work
tags: [ 'api_platform.filter' ]
...
我还查看了有关编写自定义过滤器的文档,但据我所知,它必须是现有属性。
解决方法
您定义的过滤器扩展了 ORM 过滤器 (api_platform.doctrine.orm.search_filter
),这意味着最终过滤器将转换为数据库查询。
在检索行之后之前,您的“计算字段”值是未知的,因此过滤器无法自动转换为查询。
您可以在 startDate
和 endDate
上添加“日期”过滤器并让用户使用它们进行过滤,或者实现一两个 custom ORM filters 以将此内部逻辑公开给 API 使用者。