Search code examples
phpsymfonydoctrinearraycollection

How can I get data from my ArrayCollection?


I am trying to load data from my array collection via doctrine:

 $pages = $this->em->getRepository(Pages::class)->findAll();

The result is:

2 => Pages^ {#1598 ▼
-id: 3
-name: "cat"
-membergroup: PersistentCollection^ {#1603 ▼
  -snapshot: []
  -owner: Pages^ {#1598}
  -association: array:16 [ …16]
  -em: EntityManager^ {#278 …11}
  -backRefFieldName: "pages"
  -typeClass: ClassMetadata {#693 …}
  -isDirty: false
  #collection: ArrayCollection^ {#1604 ▼
    -elements: []
  }
  #initialized: false
}

}

The problem is, that I am expecting one element to be in the membergroup ArrayCollection. But it is empty.


Solution

  • This is related to the way Doctrine works. If you use findAll(), your collections will be lazy loaded. If you try to iterate over the collection and access elements you will see that it is not empty!

    However, lazy-loaded collections are often not a good idea because it will result in an impresive amount of SQL queries. There are several way to fix this but this is not related to the question. You could for example make your own query in the repository to avoid that.

    This is known as the N+1 problem and it is a common problem for all ORMs