我在 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
}
}
]
}
它工作正常,但这不是我想要做的:(我怀疑解决方案可能是以某种方式颠倒实体的保存顺序。如果先保存帖子,然后保存类别,这应该可行。
如何正确保存这个关联?
最佳答案
不知道这是否仍然与您相关,但解决方案非常简单。
你应该配置一个 Accessor与协会的二传手,例如:
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
* @Type("ArrayCollection<Platform\BlogBundle\Entity\Post>")
* @Accessor(setter="setPosts")
*/
protected $posts;
序列化程序将调用 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;
}
关于php - symfony2 JMSSerializerBundle 反序列化具有 OneToMany 关联的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29939705/