我在doctrine2设置中有Category
OneToMany
Post
关联,如下所示:
类别:
...
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
* @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
*/
protected $posts;
...
发表:
...
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
* @Type("Platform\BlogBundle\Entity\Category")
*/
protected $category;
...
我正在尝试反序列化以下json对象(数据库中已存在id为1的两个实体)
{
"id":1,
"title":"Category 1",
"posts":[
{
"id":1
}
]
}
使用JMSSerializerBundle序列化程序使用doctrine对象构造函数配置的反序列化方法
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
}
}
]
}
它工作正常,但这不是我想做的事情:(我怀疑解决方案可能会以某种方式扭转实体保存的顺序。如果帖子先保存,类别第二,这应该有效。
如何正确保存此关联?
答案 0 :(得分:0)
不知道这是否仍然适合您,但解决方案非常直接。
您应该为Accessor配置一个关联的setter,例如:
inner_function
序列化程序将调用setter方法从json填充outer_function
。其余的逻辑应该在/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
* @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
* @Accessor(setter="setPosts")
*/
protected $posts;
:
posts