Api Platform GraphQL地址字段非必填验证异常求助
问题背景
使用PHP 8.1 + Symfony 6.1.x + Api-Platform 3.0.3,定义了Customer和CustomerAddress两个实体,其中Customer的address字段为可空非必填。通过REST接口可正常创建无address的Customer,但使用GraphQL的mutation创建时,不传address会报错:
Field createCustomerInput.address of required type createCustomerAddressNestedInput! was not provided.
问题原因
这不是Api Platform的Bug,而是GraphQL输入类型的默认配置逻辑导致的:Api Platform在生成GraphQL输入类型时,默认会将关联字段标记为必填(带!),即使实体中该字段已设置为可空。这种差异源于GraphQL类型系统与REST字段校验逻辑的设计区别,需要显式配置来覆盖默认行为。
解决方法
你需要在Customer实体的address字段上,针对GraphQL的mutation操作显式声明该字段为可空,有两种实现方式:
方式1:注解配置
在Customer实体的address字段上添加#[ApiProperty]注解,指定GraphQL的create和update操作的nullable属性为true:
use ApiPlatform\Metadata\ApiProperty; use App\Entity\CustomerAddress; class Customer { // ... 其他字段定义 #[ApiProperty( graphql: [ 'create' => ['nullable' => true], 'update' => ['nullable' => true] // 若更新操作也允许address为空,需添加此行 ] )] private ?CustomerAddress $address = null; // ... 构造函数及其他方法 }
方式2:YAML配置文件
在config/api_platform/resources/Customer.yaml(无则创建)中添加如下配置:
App\Entity\Customer: properties: address: graphql: create: nullable: true update: nullable: true # 按需配置更新操作的可空性
配置完成后,Api Platform会自动更新GraphQL Schema,此时createCustomerInput中的address字段将不再是必填类型(移除!标记),不传该字段即可正常创建无地址的Customer。
内容的提问来源于stack exchange,提问作者tsdevelopment

