2012-12-31 51 views
0

在閱讀了Doctrine參考和Symfony教程之後,我開始將它集成到一個項目中。我遇到了一個我認爲主義可以解決的問題:學說 - 如何保持ManyToOne同步?

我想Libraries與許多Collections,我認爲這是一個'ManytoOne'關係作爲集合將保持外鍵。

一些片段:

在圖書館:

/** 
* 
* @var ArrayCollection 
* 
* @ORM\OneToMany(targetEntity="Collection", mappedBy="library") 
*/ 
private $collections; 

在集合:

/** 
* @var Library 
* 
* @ORM\ManyToOne(targetEntity="Library", inversedBy="collections") 
* @ORM\JoinColumn(name="library_id", referencedColumnName="id") 
*/ 
private $library; 

由於大多數這種註釋是默認的,並可能被排除這是一個非常基本的設置。

樣品控制器代碼:

$library = new Library(); 
    $library->setName("Holiday"); 
    $library->setDescription("Our holiday photos"); 

    $collection = new Collection(); 
    $collection->setName("Spain 2011"); 
    $collection->setDescription("Peniscola"); 

    $library->addCollection($collection); 

    $em=$this->getDoctrine()->getManager(); 
    $em->persist($collection); 
    $em->persist($library);   
    $em->flush(); 

上面的代碼將不設置在Collection表,我假設是因爲Library不是所有者的library_id柱。

$library = new Library(); 
    $library->setName("Holiday"); 
    $library->setDescription("Our holiday photos"); 

    $collection = new Collection(); 
    $collection->setName("Spain 2011"); 
    $collection->setDescription("Peniscola"); 

    $collection->setLibrary($library); <--- DIFFERENCE HERE 

    $em = $this->getDoctrine()->getManager(); 
    $em->persist($collection); 
    $em->persist($library); 
    $em->flush(); 

工程。但我想能夠使用庫添加和刪除方法。

修改這些添加和刪除方法以調用setLibrary方法是否很常見?

public function addCollection(\MediaBox\AppBundle\Entity\Collection $collections) 
{ 
    $this->collections[] = $collections; 
    $collections->setLibrary($this); 
    return $this; 
} 

public function removeCollection(\MediaBox\AppBundle\Entity\Collection $collections) 
{ 
    $this->collections->removeElement($collections); 
    $collections->setLibrary(null); 
} 

我不認爲這是非常好的。

在學說或ORM中是否是最佳實踐?

親切的問候和感謝提前!

回答