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. No matter how many objects are there in collection it always returns last.
Page Entity:
/** * @ORMOneToMany(targetEntity="Language", mappedBy="page", cascade={"ALL"}, indexBy="page_id") */ private $languages;
Language entity:
/** * @ORMManyToOne(targetEntity="Page", inversedBy="languages") */ private $page; public function addLanguage(AppBundleEntityLangaugee $language) { $this->languages[] = $language; return $this; } public function removeLanguage(AppBundleEntityLanguage $language) { $this->$languages->removeElement($language); } public function getLanguages() { return $this->languages; }
Page object is fetching in 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
Did anyone had this problem?
Advertisement
Answer
After thorough debugging, I figure it out that indexBy is misused here. 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