When does Doctrine2 load an ArrayCollection?
Until I call a method like count or getValues, I have no data
Here is my business. I have a delegation object with a OneToMany (bidirectional) relation to the Promotion object, for example:
Promotion.php
use Doctrine\ORM\Mapping as ORM; class Promotion { protected $id; protected $delegation; }
Delegation.php
use Doctrine\ORM\Mapping as ORM; class Delegation { protected $id; public $promotions; public function __construct() { $this->promotions = new \Doctrine\Common\Collections\ArrayCollection(); } }
Now I am doing something like the following (with a specific delegation)
$promotion = new Promotion(); $promotion = new Promotion(); $promotion->setDelegation($delegation); $delegation->addPromotion($promotion); $em->persist($promotion); $em->flush();
Finding relationships in the database is fine. I have a promotion line with a delegation rule. And now my problem arises: if I ask for $ delega-> getPromotions (), I get an empty PersistenCollection, but if I ask for the collection method, for example $ delegation> getPromotions () โ count (), everything will be OK from here. I get the number correctly. By now setting $ delegation-> getPromotions () after this, I also get the PersistenCollection correctly.
Why is this happening? When does Doctrine2 load a collection?
Example:
$delegation = $em->getRepository('Bundle:Delegation')->findOneById(1); var_dump($delegation->getPromotions()); //empty var_dump($delegation->getPromotions()->count()); //1 var_dump($delegation->getPromotions()); //collection with 1 promotion
I could request directly the stock โ getValues โโ() and get it in order, but I would like to know what is happening and how to fix it.
As flu explains here, Doctrine2 uses proxy classes for lazy loading almost everywhere. But accessing $ delegation-> getPromotions () should automatically call the appropriate selection.
var_dump gets an empty collection, but, for example, uses it in a foreach statement, it works fine.