Doctrine2多对一双向关系不起作用 [英] Doctrine2 Many-to-one bidirectional relationship not working
问题描述
这是代码的重要部分: p>
Acme\BookBundle\Entity\Book;
code> / **
* @ ORM\ManyToOne(targetEntity =Acme\UserBundle\Entity\User,inversedBy =owned_books)
* @ ORM\JoinColumn (name =owner_id,referencedColumnName =id)
* /
protected $ owner;
/ **
*获取所有者
*
* @return Acme\UserBundle\Entity\User
* /
public function getOwner()
{
return $ this-> owner;
}
Acme\UserBundle\Entity\User; strong>
/ **
* @ ORM\OneToMany(targetEntity =Acme\BookBundle\Entity \Book,mappedBy =owner)
* /
protected $ owned_books;
public function __construct()
{
$ this-> owned_books = new \Doctrine\Common\Collections\ArrayCollection();
}
/ **
*获得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();
这不工作(提供致命错误:调用未定义的方法Doctrine\ORM\PersistentCollection :: getName())
$ owner = $ this-> getDoctrine()
- > getRepository('UserBundle:User')
- > find(1);
$ books = $ owner-> getOwnedBooks() - > getName();
有谁知道我做错了什么?谢谢你提前。
$ owner-> getOwnedBooks()是一个所有者的集合。尝试用foreach循环循环遍历集合。
$ books = $ owner-> getOwnedBooks();
foreach($ books as $ book){
echo $ book-> getName()。 '< br />';
}
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.
$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/>';
}
这篇关于Doctrine2多对一双向关系不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!