多对一双向关系不起作用

多对一双向关系不起作用

本文介绍了Doctrine2 多对一双向关系不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 2 个实体之间进行双向关联.问题是,我可以从 Book 获得他们的所有者,但从 Owner 我无法获得拥有的图书.

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.

这是代码的重要部分:

AcmeBookBundleEntityBook;

/**
 * @ORMManyToOne(targetEntity="AcmeUserBundleEntityUser", inversedBy="owned_books")
 * @ORMJoinColumn(name="owner_id", referencedColumnName="id")
 */
protected $owner;

/**
 * Get owner
 *
 * @return AcmeUserBundleEntityUser
 */
public function getOwner()
{
    return $this->owner;
}

AcmeUserBundleEntityUser;

/**
 * @ORMOneToMany(targetEntity="AcmeBookBundleEntityBook", mappedBy="owner")
 */
protected $owned_books;

public function __construct()
{
    $this->owned_books = new DoctrineCommonCollectionsArrayCollection();
}

/**
 * Get owned_books
 *
 * @return DoctrineCommonCollectionsCollection
 */
public function getOwnedBooks()
{
    return $this->owned_books;
}

然后,获取数据:

这可行

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

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

这不起作用(给出致命错误:调用未定义的方法 DoctrineORMPersistentCollection::getName())

This Doesn't work ( Gives Fatal error: Call to undefined method DoctrineORMPersistentCollection::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() 是 Owners 的集合.尝试使用 foreach 循环遍历集合.

$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 多对一双向关系不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:58