简体   繁体   English

symfony @oneToMany 关系只返回集合中的最后一个对象

[英]symfony @oneToMany relation returns only last object in collection

I have a situation and not really sure what I'm doing wrong.我有一个情况,并不确定我做错了什么。 in Sumfony 3.3 I've created a relation between entity Page and Language, where Page is related to multiple Languages, and when I search for a Page and get Page object but property Languages returns collection with only last Language object.在 Sumfony 3.3 中,我创建了实体 Page 和 Language 之间的关系,其中 Page 与多种语言相关,当我搜索 Page 并获取 Page 对象但属性 Languages 返回仅包含最后一个 Language 对象的集合时。 No matter how many objects are there in collection it always returns last.无论集合中有多少对象,它总是最后返回。

Page Entity:页面实体:

/**
 * @ORM\OneToMany(targetEntity="Language", mappedBy="page", cascade={"ALL"}, indexBy="page_id")
 */
private $languages;

Language entity:语言实体:

/**
 * @ORM\ManyToOne(targetEntity="Page", inversedBy="languages")
 */
private $page;

public function addLanguage(\AppBundle\Entity\Langaugee $language)
{
    $this->languages[] = $language;

    return $this;
}

public function removeLanguage(\AppBundle\Entity\Language $language)
{
    $this->$languages->removeElement($language);
}

public function getLanguages()
{
    return $this->languages;
}

Page object is fetching in PageService: Page 对象正在 PageService 中获取:

public function getPageByName($name)
{
return $this->pageRepository->findBy(array("name"=>$name));
}

Since property $languages by default set on lazy, JMS serializer when serializes Page object it's fetching languages collection由于属性 $languages 默认设置为惰性,JMS 序列化程序在序列化 Page 对象时它正在获取语言集合

Did anyone had this problem?有没有人遇到过这个问题?

After thorough debugging, I figure it out that indexBy is misused here.经过彻底调试后,我发现 indexBy 在这里被滥用了。 Defined indexBy = page_id provided always the same value so every record that is mapped to entity in SimpleObjectHydrator overrun the existing record, leaving only last added Language object in collection定义的 indexBy = page_id 始终提供相同的值,因此在 SimpleObjectHydrator 中映射到实体的每条记录都会覆盖现有记录,只留下最后添加的 Language 对象在集合中

I know Its an old post, but solution below worked for me.我知道这是一个旧帖子,但下面的解决方案对我有用。

I had to clear EntityManager cache in my repository class method by calling this method just before fetching data.我必须通过在获取数据之前调用此方法来清除存储库类方法中的 EntityManager 缓存。

$this->_em->clear();

here _em is the default EntityManager available in the repository class.这里_em是存储库类中可用的默认EntityManager

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

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