多对多关联的 POST 请求 [英] POST request on many-to-many association

查看:28
本文介绍了多对多关联的 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有多对多关联的实体:

I have two entities with a many-to-many association:

class User extends BaseUser

class Calendar
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="text")
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="view", type="text")
     * @Assert\Choice(choices = {"work week", "week", "month", "year"}, message = "Choose a valid view.")
     */
    private $view;

    /**
     * @ManyToMany(targetEntity="AppBundle\Entity\User")
     * @JoinTable(name="calendars_publishers",
     *      joinColumns={@JoinColumn(name="calendar_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="publisher_id", referencedColumnName="id", unique=true)}
     *      )
     */
    private $publishers;

    public function __construct()
    {
        $this->publishers = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
      * Add publishers
      *
      * @param \AppBundle\Entity\User $publishers
      * @return Calendar
      */
      public function addPublisher(\AppBundle\Entity\User $publishers)
       {
          $this->publishers[] = $publishers;

           return $this;
       }

      /**
        * Remove publishers
        *
        * @param \AppBundle\Entity\User $publishers
        */
       public function removePublisher(\AppBundle\Entity\User $publishers)
     {
         $this->publishers->removeElement($publishers);
      }
}

当我对 REST API 执行 POST 请求时(http://localhost:8000/calendars)与身体:

And when I do a POST request on my REST API (http://localhost:8000/calendars) with the body:

{
  "name": "My calendar",
  "view": "week",
  "publishers": [
    "/users/1",
    "/users/2"
  ]
}

我有回复:

{
  "@context": "/contexts/Calendar",
  "@id": "/calendars/3",
  "@type": "Calendar",
  "name": "My calendar",
  "view": "week",
  "publishers": []
}

所以,如您所见,我的对象记录得很好,但我无法将某些用户放入 publishers.你有什么想法吗?

So, as you see, my object is recorded well, but I cannot put some users in publishers. Do you have an idea?

我使用捆绑包:

  • DunglasApiBundle
  • NelmioApiDocBundle
  • NelmioCorsBundle
  • FOSHttpCacheBundle
  • FOSUserBundle
  • LexikJWTAuthenticationBundle

使用 api-platform.

推荐答案

你应该添加 addPublisher(User $publisher)removePublisher(User $publisher) 方法.

You should add addPublisher(User $publisher) and removePublisher(User $publisher) methods.

API Platform 内部使用了 Symfony PropertyAccess 组件,该组件需要这样的方法才能访问私有属性.

API Platform internally uses the Symfony PropertyAccess component, and this component requires such methods to be able to access to the private property.

这篇关于多对多关联的 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆