2

I have an Entity that has bidirectional ManyToOne/OneToMany relationship with another entity:

class BookShelf {
  /** 
  * @OneToMany(targetEntity="Book", mappedBy="shelf", cascade={"persist"})
  */
 public $books;
}
class Book {
  /** 
  * @ManyToOne(targetEntity="BookShelf", inversedBy="books", cascade={"persist"})
  */
 public $shelf;
}

I'm trying to create a new book, and have that object be listed in the bookshelf.

$book = new Book();
$book->shelf = $shelf;
$em->persist($book); $em->flush();
$shelf->showBooks();

After that, the $shelf->books does not contain the book, but instead it contains NULL. However the book is correctly inserted into the database, and when I run $shelf->showBooks() on another pageload, the book is listed properly.

I tried adding $em->refresh($book) and $em->refresh($shelf) but it doesn't help, the association still isn't refreshed.

Doctrine manual does suggest that I could use $shelf->books->add($book) to manually synchronize the association, but since there are initially no books, $shelf->books is NULL and I cannot call any methods on it.

How can I make Doctrine reload the association to include the newly created associated entity?

(Related: "Doctrine and unrefreshed relationships")

4

1 回答 1

1

正如我后来注意到的那样,我链接到的同一个Doctrine 手册告诉我在构造函数中将属性设置为 ArrayCollection,这样$shelf->books->add($book) 才能正常工作。那是:

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

愚蠢的我。我会在这里发布答案,以防其他人在同样愚蠢之后碰巧来寻找同样的问题。我猜这不太可能。

于 2013-07-11T11:47:47.357 回答