Php symfony2 JMSSerializerBundle使用OneToMany关联反序列化实体
我在doctrine2设置中有Php symfony2 JMSSerializerBundle使用OneToMany关联反序列化实体,php,symfony,doctrine-orm,associations,jmsserializerbundle,Php,Symfony,Doctrine Orm,Associations,Jmsserializerbundle,我在doctrine2设置中有类别
类别
Post
关联,如下所示:
类别:
...
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
* @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
*/
protected $posts;
...
我正在尝试反序列化以下json对象(数据库中已经存在id为1的两个实体)
使用JMSSerializerBundle序列化程序的反序列化方法,该方法配置为条令对象构造函数
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
public: false
结果如下:
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
}
]
}
}
乍一看很好。问题是,关联的Post
将category
字段设置为null
,导致persist()
上没有关联。如果我尝试将其反序列化:
{
"id":1,
"title":"Category 1",
"posts":[
{
"id":1
"category": {
"id":1
}
}
]
}
它工作得很好,但这不是我想做的:(我怀疑解决方案可能是以某种方式颠倒实体保存的顺序。如果文章先保存,类别第二保存,这应该会起作用
如何正确保存此关联?不知道这是否仍然与您相关,但解决方案非常简单 您应该为关联配置setter,例如:
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
* @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
* @Accessor(setter="setPosts")
*/
protected $posts;
{
"id":1,
"title":"Category 1",
"posts":[
{
"id":1
"category": {
"id":1
}
}
]
}
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
* @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
* @Accessor(setter="setPosts")
*/
protected $posts;
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;
}