要解决这个问题,需要在API资源类中设置属性的访问级别为public。默认情况下,API资源类中的所有属性都是只读的,即使在Symfony实体类中声明为可写。
示例代码:
use ApiPlatform\Core\Annotation\ApiResource; use Symfony\Component\Serializer\Annotation\Groups;
/**
@ApiResource(
normalizationContext={"groups"={"user:read"}},
denormalizationContext={"groups"={"user:write"}}
) / class User { /*
/**
/**
在上面的代码中,$id属性被设置为public,因此它既可以被读取也可以被写入。但是,$username属性只能被读取,因为它是只读的。相反,$password属性只能被写入,因为它是可写的。
通过在Groups注释中使用“user:read”和“user:write”,您可以为每个属性指定相应的访问级别。这将使您能够在API资源中实现更精细的控制。