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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:47:22