symfony2 JMSSerializerBundle使用OneToMany关联反序列化实体

Jiř*_*bec 5 php associations symfony doctrine-orm jmsserializerbundle

Category OneToMany Post在doctrine2设置中有这样的关联:

类别:

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

帖子:

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

我试图反序列化后面的json对象(数据库中已存在id为1的两个实体)

{
    "id":1,
    "title":"Category 1",
    "posts":[
        {
            "id":1
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

使用JMSSerializerBundle序列化程序的deserialize方法配置了doctrine对象构造函数

jms_serializer.object_constructor:
    alias: jms_serializer.doctrine_object_constructor
    public: false
Run Code Online (Sandbox Code Playgroud)

结果如下:

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
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

这是第一眼就好了.问题是,相关的Postcategory字段设置为null,导致上没有关联persist().如果我尝试反序列化:

{
    "id":1,
    "title":"Category 1",
    "posts":[
        {
            "id":1
            "category": {
                "id":1
            }
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但这不是我想要做的:(我怀疑解决方案可能以某种方式扭转实体保存的顺序.如果帖子先保存,类别第二,这应该工作.

如何正确保存这种关联?

ori*_*nal 2

不知道这是否仍然与您相关,但解决方案非常简单。

您应该为关联配置一个具有设置器的访问器,例如:

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

序列化器将调用 setter 方法从 json 中填充posts。其余逻辑应在以下内部处理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's 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;
}
Run Code Online (Sandbox Code Playgroud)