Reputation: 1564
I'm trying to do a bidirectional association between 2 entities. The problem is that from Book I can get their Owner, but from Owner I can't get the books owned.
Here is the important part of the code:
Acme\BookBundle\Entity\Book;
/**
* @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;
}
Acme\UserBundle\Entity\User;
/**
* @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;
}
Then, to get the data:
This Works
$book = $this->getDoctrine()
->getRepository('BookBundle:Book')
->find(1);
$owner = $book->getOwner()->getFirstName();
This Doesn't work ( Gives Fatal error: Call to undefined method Doctrine\ORM\PersistentCollection::getName() )
$owner = $this->getDoctrine()
->getRepository('UserBundle:User')
->find(1);
$books = $owner->getOwnedBooks()->getName();
Does anyone know what I'm doing wrong? Thank you in advance.
Upvotes: 3
Views: 6581
Reputation: 784
$owner->getOwnedBooks() is a collection of Owners. Try to loop through the collection with a foreach loop.
$books = $owner->getOwnedBooks();
foreach ($books as $book) {
echo $book->getName() . ' <br/>';
}
Upvotes: 10
Reputation: 23265
The error message is pretty clear: you're trying to get the name of a collection of book, instead of trying to get the name of a single book.
Upvotes: 3