2015-04-29 60 views
4

我在doctrine2設置CategoryOneToManyPost協會這樣的:Symfony2的JMSSerializerBundle反序列化實體

類別:

... 
/** 
* @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串行器的反序列化方法與教義對象構造

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

不知道這是否仍然適用於你,但該解決方案是非常簡單。

你應該配置Accessor機智h對於的關聯的設定器,例如:

/** 
* @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; 
} 
相關問題