【问题标题】:Doctrine2 Many-to-one bidirectional relationship not workingDoctrine2 多对一双向关系不起作用
【发布时间】:2012-06-14 08:32:51
【问题描述】:

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

这是代码的重要部分:

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;
}

然后,获取数据:

这可行

$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();

有谁知道我做错了什么?提前谢谢你。

【问题讨论】:

    标签: symfony doctrine doctrine-orm


    【解决方案1】:

    $owner->getOwnedBooks() 是所有者的集合。尝试使用 foreach 循环遍历集合。

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

    【讨论】:

      【解决方案2】:

      错误消息非常清楚:您正在尝试获取书籍集合的名称,而不是尝试获取单本书的名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-06
        • 1970-01-01
        • 1970-01-01
        • 2013-12-05
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多