Symfony2 JMSSerializerBundle Deserializes an Object Using OneToMany Association

I have a connection Category OneToMany Postin a doctrine2 installation as follows:

Category:

...
/**
 * @ORM\OneToMany(targetEntity="Post", mappedBy="category")
 * @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
 */
protected $posts;
...

Message:

...
/**
 * @ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
 * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
 * @Type("Platform\BlogBundle\Entity\Category")
 */
protected $category;
...

I am trying to deserialize the following json object (both objects with id of 1 already exist in the database)

{
    "id":1,
    "title":"Category 1",
    "posts":[
        {
            "id":1
        }
    ]
}

using the JMSSerializerBundle serializer deserialization method configured using the doctrine object constructor

jms_serializer.object_constructor:
    alias: jms_serializer.doctrine_object_constructor
    public: false

with the following result:

Platform\BlogBundle\Entity\Category {#2309
  #id: 1
  #title: "Category 1"
  #posts: Doctrine\Common\Collections\ArrayCollection {#2314
    -elements: array:1 [
      0 => Platform\BlogBundle\Entity\Post {#2524
        #id: 1
        #title: "Post 1"
        #content: "post 1 content"
        #category: null
      }
    ]
  }
}

This is normal at first sight. The problem is that the bound Posthas a field Categoryset to null, which does not lead to an association on persist(). If I try to deserialize this:

{
    "id":1,
    "title":"Category 1",
    "posts":[
        {
            "id":1
            "category": {
                "id":1
            }
        }
    ]
}

, , :( , - . , .

?

+4
1

, , .

Accessor , :

/**
 * @ORM\OneToMany(targetEntity="Post", mappedBy="category")
 * @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
 * @Accessor(setter="setPosts")
 */
protected $posts;

setter posts json. setPosts:

public function setPosts($posts = null)
{
    $posts = is_array($posts) ? new ArrayCollection($posts) : $posts;
    // a post is the owning side of an association so you should ensure
    // that its category will be nullified if it not longer in a collection
    foreach ($this->posts as $post) {
        if (is_null($posts) || !$posts->contains($post) {
            $post->setCategory(null);
        }
    }
    // This is what you need to fix null inside the post.category association
    if (!is_null($posts)) {
        foreach ($posts as $post) {
            $post->setCategory($this);
        }
    }

    $this->posts = $posts;
}
0

All Articles