2012-12-31 5 views
0

Doctrine 레퍼런스와 Symfony 튜토리얼을 읽은 후 프로젝트에 통합하기 시작했습니다. 나는 교리가 풀 수 있다고 생각한 문제를 겪고 있습니다 : Libraries을 많은 Collections과 같이 갖고 싶습니다. 이것은 외래 키를 보관할 것이므로 'ManytoOne'관계라고 가정합니다.Doctrine - 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(); 

위의 코드는 내가 Library가 소유자가 아닌 때문입니다 가정합니다 Collection 테이블에서 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에서 가장 좋은 방법입니까?

친절에 감사드립니다.

답변

관련 문제