【问题标题】:API Platform - Adding new entity with subresourceAPI 平台 - 添加具有子资源的新实体
【发布时间】:2021-12-21 18:13:00
【问题描述】:

据我所知,这是不可能的,但我想我会问一下,以防我错过了什么。

我有 2 个实体,规则和条件

一个规则可以有多个条件

我想要实现的是在单个请求中添加具有一个或多个条件的新规则

我已经通过 POST 尝试了以下操作

{
  "property": "id",
  "conditions": [
    {
        "position": 1
    }
  ],
  "title": "getId",
  "position": 1
}

Conditions 有一个 rule_id 列,但是我现在显然不能设置它,因为它还没有被创建

那个请求给了我错误

Nested documents for attribute "conditions" are not allowed. Use IRIs instead.

当然,我不能使用 IRI,因为我还没有创建条件,而且我不能先创建条件,因为它会导致外键检查失败

那么我认为这是不可能的,还是我做错了?

提前致谢

【问题讨论】:

    标签: api-platform.com


    【解决方案1】:

    您需要将相同的序列化组添加到RuleCondition 类中,如here 所述。

    您还必须将cascade={"persist"} 属性添加到Rule::conditions 属性的@OneToMany 注释中。

    类似的东西:

    // src/EntityRule.php
    
    #[ORM\Entity(repositoryClass: RuleRepository::class)]
    #[ApiResource(
        collectionOperations: [
            "post" => [
                "denormalization_context" => [ "groups" => ["write:rule"]]
            ]
        ]
    )]
    class Rule
    {
        // ...
        
        #[ORM\OneToMany(mappedBy: "rule", targetEntity: Condition::class, cascade: ["persist"])]
        #[Groups(["write:rule"])]
        /**
         * @var Condition[]
         */
        private Collection $conditions;
    
        // ...
    }
    
    // src/Entity/Condition.php
    
    #[ORM\Entity(repositoryClass: ConditionRepository::class)]
    #[ApiResource(
        collectionOperations: [
            "post" => [
                "denormalization_context" => ["groups" => ["write:condition"]
                ]
            ]
        ]
    )]
    class Condition
    {
        // ...
    
        #[ORM\Column(nullable=false, unique=false)]
        #[Groups(["write:condition", "write:rule"])]
        private int $position;
    
        // ...
    }
    

    【讨论】:

    • 谢谢,这正是我所需要的。一个注释以防其他人阅读此内容,我必须将级联部分更改为cascade={"persist"}
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多