You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ApiPlatform GraphQL嵌套DTO使用报错及结构异常问题咨询

ApiPlatform中GraphQL使用DTO遇到的问题

我在ApiPlatform中尝试使用DTO,编写了以下代码:

RequestDto类(包含note属性及嵌套的UserDto)

<?php

namespace App\ApiPlatform\DTO;

class RequestDto
{
    public ?string $note = null;

    /**
     * @var UserDto
     */
    public UserDto $user;
}

UserDto类

<?php

namespace App\ApiPlatform\DTO;

class UserDto
{
    public string $name;
}

Request实体的ApiResource配置

为REST的Post操作和GraphQL的Mutation操作指定input为RequestDTO::class:

#[ApiPlatform\ApiResource(
    operations: [
        new ApiPlatform\Post(input: RequestDTO::class, processor: RequestProcessor::class),
    ],
    graphQlOperations: [
        new ApiPlatform\GraphQl\Query(),
        new ApiPlatform\GraphQl\Mutation(
            name: 'create',
            input: RequestDTO::class,
            processor: RequestProcessor::class,
        ),
    ],
)]
class Request {
...
}

现象对比

  • 使用REST API时,可正常识别嵌套结构:
{
  "note": "string",
  "user": {
    "name": "string"
  }
}
  • 使用GraphQL Schema时,仅显示:
note: String
clientMutationId: String

同时出现错误:

Case mismatch between loaded and declared class names: "App\ApiPlatform\DTO\RequestDTO" vs "App\ApiPlatform\DTO\RequestDto"

我的环境:Symfony 7.1.6、ApiPlatform 4.0.10、PHP 8.3.13、MacOS。请问这是Bug还是GraphQL不支持使用DTO?


解决方法

这既不是Bug,也不是GraphQL不支持DTO,问题出在类名大小写不匹配:

  1. 实际类名是RequestDto,但配置里写的是RequestDTO::class。MacOS默认的APFS文件系统不区分大小写,PHP能正常加载类,但ApiPlatform的GraphQL组件对类名大小写敏感,导致无法正确识别DTO结构,因此Schema里不显示user字段。
  2. 修正配置中的类名,把所有RequestDTO::class替换为RequestDto::class:
#[ApiPlatform\ApiResource(
    operations: [
        new ApiPlatform\Post(input: RequestDto::class, processor: RequestProcessor::class),
    ],
    graphQlOperations: [
        new ApiPlatform\GraphQl\Query(),
        new ApiPlatform\GraphQl\Mutation(
            name: 'create',
            input: RequestDto::class,
            processor: RequestProcessor::class,
        ),
    ],
)]
class Request {
...
}
  1. 清除Symfony缓存:
php bin/console cache:clear
  1. 重新访问GraphQL Playground,就能看到包含嵌套user字段的正确Schema结构。

内容的提问来源于stack exchange,提问作者evzzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:12:41