Api Platform含ReferenceMany关联的端点POST请求报错求助
解决Api Platform中MongoDB ReferenceMany关联的反序列化问题
1. 给关联属性配置反序列化规则
直接在AclGroup类的acls属性上,加上Api Platform的#[ApiProperty]注解,指定反序列化时的集合类型为ArrayCollection:
use ApiPlatform\Metadata\ApiProperty; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB; class AclGroup { // 其他属性省略 #[MongoDB\ReferenceMany(targetDocument: Action::class)] #[ApiProperty( deserializationContext: [ 'collection_type' => ArrayCollection::class ] )] private ArrayCollection $acls; // 构造函数里初始化集合 public function __construct() { $this->acls = new ArrayCollection(); } }
2. 使用正确的请求格式
发送POST请求时,直接传Action的IRI数组就行,不用手动转ArrayCollection,示例请求体:
{ "name": "管理员组", "acls": [ "/api/actions/1", "/api/actions/2" ] }
3. 检查序列化组(如果用到的话)
如果你的资源配置了序列化组,得确保acls属性被包含在反序列化组里:
use ApiPlatform\Metadata\ApiResource; use Symfony\Component\Serializer\Annotation\Groups; #[ApiResource( normalizationContext: ['groups' => ['acl_group:read']], denormalizationContext: ['groups' => ['acl_group:write']] )] class AclGroup { // 其他属性省略 #[MongoDB\ReferenceMany(targetDocument: Action::class)] #[ApiProperty(deserializationContext: ['collection_type' => ArrayCollection::class])] #[Groups(['acl_group:read', 'acl_group:write'])] private ArrayCollection $acls; }
4. 自定义反序列化器(以上方法无效时用)
要是默认的反序列化逻辑还是不生效,就自己写个反序列化器处理数组转ArrayCollection:
use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; class ArrayCollectionDenormalizer implements DenormalizerInterface { public function denormalize($data, string $type, string $format = null, array $context = []) { return new ArrayCollection($data); } public function supportsDenormalization($data, string $type, string $format = null) { return $type === ArrayCollection::class && is_array($data); } }
然后在services.yaml里注册这个服务:
services: App\Serializer\ArrayCollectionDenormalizer: tags: ['serializer.denormalizer']
内容的提问来源于stack exchange,提问作者mkultra
相关产品推荐
相关产品推荐

