php - symfony2 JMSSerializerBundle deserialize entity with OneToMany association -
i have category onetomany post association in doctrine2 setup this:
category:
... /** * @orm\onetomany(targetentity="post", mappedby="category") * @type("arraycollection<platform\blogbundle\entity\post>") */ protected $posts; ... post:
... /** * @orm\manytoone(targetentity="category", inversedby="posts") * @orm\joincolumn(name="category_id", referencedcolumnname="id") * @type("platform\blogbundle\entity\category") */ protected $category; ... i trying deserialize following json object (both entities id of 1 exist in database)
{ "id":1, "title":"category 1", "posts":[ { "id":1 } ] } using jmsserializerbundle serializer's deserialize method configured doctrine object constructor
jms_serializer.object_constructor: alias: jms_serializer.doctrine_object_constructor public: false with 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 } ] } } which fine @ first sight. problem is, associated post has category field set null, resulting in no association on persist(). if try deserialize this:
{ "id":1, "title":"category 1", "posts":[ { "id":1 "category": { "id":1 } } ] } it works fine not want :( suspect solution somehow reverse order in entities saved. if post saved first , category second, should work.
how save association properly?
don't know whether still relevant solution pretty straight.
you should configure accessor setter association, e.g.:
/** * @orm\onetomany(targetentity="post", mappedby="category") * @type("arraycollection<platform\blogbundle\entity\post>") * @accessor(setter="setposts") */ protected $posts; the serializer call setter method populate posts json. rest of logic should handled inside setposts:
public function setposts($posts = null) { $posts = is_array($posts) ? new arraycollection($posts) : $posts; // post owning side of association should ensure // category nullified if it's not longer in collection foreach ($this->posts $post) { if (is_null($posts) || !$posts->contains($post) { $post->setcategory(null); } } // need fix null inside post.category association if (!is_null($posts)) { foreach ($posts $post) { $post->setcategory($this); } } $this->posts = $posts; }
Comments
Post a Comment