如何注册自定义 DQL 函数
Doctrine 允许你指定自定义 DQL 函数。关于此主题的更多信息,请阅读 Doctrine 的 cookbook 文章 DQL 用户自定义函数。
在 Symfony 中,你可以按如下方式注册你的自定义 DQL 函数
1 2 3 4 5 6 7 8 9 10 11 12
# config/packages/doctrine.yaml
doctrine:
orm:
# ...
dql:
string_functions:
test_string: App\DQL\StringFunction
second_string: App\DQL\SecondStringFunction
numeric_functions:
test_numeric: App\DQL\NumericFunction
datetime_functions:
test_datetime: App\DQL\DatetimeFunction
注意
如果 entity_managers
被显式命名,直接使用 ORM 配置函数将会触发异常 Unrecognized option "dql" under "doctrine.orm"
。dql
配置块必须在已命名的实体管理器下定义。
1 2 3 4 5 6 7 8 9 10
# config/packages/doctrine.yaml
doctrine:
orm:
# ...
entity_managers:
example_manager:
# Place your functions here
dql:
datetime_functions:
test_datetime: App\DQL\DatetimeFunction
警告
DQL 函数由 Doctrine 在 Symfony 服务容器 之外实例化,因此你无法将服务或参数注入到自定义 DQL 函数中。
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。