2012-06-14 2 views
3

두 엔티티간에 양방향 연결을 시도하고 있습니다. 문제는 책에서 소유자를 얻을 수 있지만 소유자는 책을 소유 할 수 없다는 것입니다. 여기 Doctrine2 다 대일 양방향 관계가 작동하지 않습니다.

코드의 중요한 부분입니다 :

한국 전기 \ BookBundle \ 엔티티 \ 예약;

/** 
* @ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="owned_books") 
* @ORM\JoinColumn(name="owner_id", referencedColumnName="id") 
*/ 
protected $owner; 

/** 
* Get owner 
* 
* @return Acme\UserBundle\Entity\User 
*/ 
public function getOwner() 
{ 
    return $this->owner; 
} 

한국 전기 \ UserBundle \ 엔티티 \ 사용자;

/** 
* @ORM\OneToMany(targetEntity="Acme\BookBundle\Entity\Book", mappedBy="owner") 
*/ 
protected $owned_books; 

public function __construct() 
{ 
    $this->owned_books = new \Doctrine\Common\Collections\ArrayCollection(); 
} 

/** 
* Get owned_books 
* 
* @return Doctrine\Common\Collections\Collection 
*/ 
public function getOwnedBooks() 
{ 
    return $this->owned_books; 
} 

그런 다음 데이터를 얻을 수 :

$book = $this->getDoctrine() 
    ->getRepository('BookBundle:Book') 
    ->find(1); 

$owner = $book->getOwner()->getFirstName(); 

을 (작동하지 않습니다 작동하는 것은 치명적인 오류를 제공 교리 \ ORM \ 정의되지 않은 메서드 호출 PersistentCollection :: getName())

$owner = $this->getDoctrine() 
    ->getRepository('UserBundle:User') 
    ->find(1); 

$books = $owner->getOwnedBooks()->getName(); 

내가 뭘 잘못하고 있는지 아는 사람 있습니까? 미리 감사드립니다.

답변

8

$ owner-> getOwnedBooks()는 Owners의 모음입니다. foreach 루프를 사용하여 컬렉션을 반복합니다.

$books = $owner->getOwnedBooks(); 
foreach ($books as $book) { 
    echo $book->getName() . ' <br/>'; 
} 
+0

그게 문제 였어, 많이 고마워! – jonfer

3

오류 메시지는 매우 명확합니다. 하나의 책 이름을 얻는 대신 책 모음 이름을 얻으려고합니다.

+0

당신이 맞아요, 고마워요. :) – jonfer

관련 문제