ApiPlatform 的 GraphQL 入口默认未启用,需手动配置 graphql: true、安装 webonyx/graphql-php、确保 symfony/serializer ≥ 6.4,并在实体中显式声明 graphql 查询/突变及字段可读写属性。
ApiPlatform 的
入口默认不启用
装完 ApiPlatform,默认只有 REST,
端点(如
)根本不存在,访问直接 404。这不是配置漏了,是它压根没开——得手动激活。
检查
,确保有
(不是
,那是旧版写法)
确认已安装
:运行
,ApiPlatform 3.x 不再自动带它
若用 Symfony 6.4+,还要确认
版本 ≥ 6.4,否则
类型推导会报
和
类型没生成?看实体注解和资源配置
ApiPlatform 不靠 Doctrine 注解自动生成 GraphQL Schema,而是依赖资源(Resource)是否被显式暴露、以及字段是否可读/可写。哪怕实体加了
,缺关键配置照样不出字段。
实体类必须有
,只写
不生效
字段级控制靠
,
或
会直接从 Schema 消失
关联字段(如
)默认不嵌套展开,要加
才进 Query,加
才进 Mutation
执行
查询返回空对象或
常见于类型映射失败或序列化器冲突,尤其在用
、自定义 DTO 或继承实体时。错误日志往往藏在 Symfony profiler 的「Logs」里,而不是响应体中。
打开
确认
路由存在且 method 是
在
加
,然后用 GraphiQL 访问
查具体异常堆栈
避免在实体中用
直接作为属性类型;改用
并配
DTO 作
时,必须实现
且参数全可选,否则
解析器会因构造失败而静默返回空
Symfony 事件监听器在
请求中不触发
因为 ApiPlatform 的 GraphQL 层绕过了传统控制器生命周期,
、
这些事件默认不发。想插手数据读写,得换地方挂钩子。
读操作(Query)用
或
实现自定义解析器
写操作(Mutation)改写
,在
里手动调用你的业务逻辑
别试图在
里判断
—— 它永远是
或空,GraphQL 请求的 format 是隐式的
GraphQL 的 Schema 构建发生在容器编译期,不是请求时。改一个
注解后必须清缓存(
),否则开发环境也看不到变化。
GraphQLGraphQL/api/graphqlconfig/packages/api_platform.yamlgraphql: trueenabled: truewebonyx/graphql-phpcomposer require webonyx/graphql-phpsymfony/serializerGraphQLCannot autowire service "ApiPlatform\GraphQl\Type\Definition\TypeBuilder"QueryMutation@ApiResource@ApiResource(graphql: {"query": true, "mutation": true})graphql: true@ApiProperty(readable: true, writable: true)readonlywriteonly$authorgraphQlRead: truegraphQlWrite: truegraphql"message": "Internal server error"DateTimeInterfacedebug:routerapi_graphql_entrypointPOSTconfig/packages/api_platform.yamlenable_profiler: true/api/graphql?debugDateTimeDateTimeInterface@ApiProperty(schema: {"type": "string", "format": "date-time"})input__construct()GraphQLGraphQLkernel.controllerkernel.viewApiPlatform\GraphQl\Resolver\QueryItemResolverInterfaceQueryCollectionResolverInterfaceApiPlatform\GraphQl\Resolver\MutationResolverInterfaceresolve()onKernelRequest$request->getRequestFormat() === 'graphql'html@ApiPropertycache:clear