-1

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.

peace_love
  • 6,229
  • 11
  • 69
  • 157

1 Answers1

5

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

Florian Hermann
  • 750
  • 6
  • 15
  • I actually tried to make my own query `public function joinMembergroup() { return $this->createQueryBuilder('pages') ->leftJoin('pages.membergroup', 'm') ->getQuery() ->execute(); }` But the result is the same – peace_love Jun 10 '20 at 11:56
  • 3
    You are close to the answer! Just add a ->addSelect('m') and you will be ok. – Florian Hermann Jun 10 '20 at 11:57