简体   繁体   English

Doctrine OneToMany 关系的问题

[英]Issue with Doctrine OneToMany relationship

I have an issue with the doctrine relationship.我对 doctrine 关系有疑问。 I try different ways but anything won't work.我尝试不同的方法,但任何方法都行不通。 Idea is that I have a News entity and every news should have many comments.想法是我有一个新闻实体,每条新闻都应该有很多评论。 So I try next:所以我接下来尝试:

The News entity:新闻实体:

/**
 * @ORM\OneToMany(targetEntity="App\ORM\Entity\NewsComment", mappedBy="news")
 */
protected \Doctrine\Common\Collections\Collection $comments;

/**
 * News constructor.
 */
public function __construct() {
    $this->comments = new ArrayCollection();
}

And NewsComment entity:和 NewsComment 实体:

/**
 * @ORM\ManyToOne(targetEntity="App\ORM\Entity\News", inversedBy="comments")
 */
protected \App\ORM\Entity\News $news;

Every entity has its own get and set methods as well.每个实体也有自己的 get 和 set 方法。

But, when I receive a News entity a can get comments collection but it always empty.但是,当我收到新闻实体时,可以获取评论集合,但它总是空的。 On the other hand, I can take any NewsComment entity and get from this News entity.另一方面,我可以获取任何 NewsComment 实体并从该 News 实体中获取。 It is working fine.它工作正常。 But not to another way.但不是以另一种方式。

Is anything wrong with my code?我的代码有什么问题吗?

Doctrine sets owned (non-inversed) collection as lazy by default. Doctrine 默认情况下将拥有(非反转)集合设置为惰性。
When retrieving an entity by database, you should see an empty PersistentCollection instead of ArrayCollection , with initialized property set to false.当通过数据库检索实体时,您应该看到一个空的PersistentCollection而不是ArrayCollectioninitialized属性设置为 false。

When calling any method on that collection, doctrine fires the queries needed to initialize the collection and populate it.在该集合上调用任何方法时,doctrine 会触发初始化集合并填充它所需的查询。

Collection emptiness should be only checked invoking isEmpty .只有调用isEmpty才能检查集合是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM