Collections Doctrine2不';在调用方法之前,不要加载集合

Collections Doctrine2不';在调用方法之前,不要加载集合,collections,doctrine-orm,load,lazy-evaluation,arraycollection,Collections,Doctrine Orm,Load,Lazy Evaluation,Arraycollection,Doctrine2何时加载ArrayCollection? 在调用count或GetValue等方法之前,我没有数据 这是我的案子。我有一个与促销实体具有一对一(双向)关系的委托实体,如下所示: Promotion.php use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class Promotion { /** * @ORM\Id * @ORM\Column(type="integer")

Doctrine2何时加载ArrayCollection?
在调用count或GetValue等方法之前,我没有数据
这是我的案子。我有一个与促销实体具有一对一(双向)关系的委托实体,如下所示:

Promotion.php

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Promotion
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Delegation", inversedBy="promotions", cascade={"persist"})
     * @ORM\JoinColumn(name="delegation_id", referencedColumnName="id")
     */
    protected $delegation;
}
Delegation.php

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class Delegation
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Promotion", mappedBy="delegation", cascade={"all"}, orphanRemoval=true)
     */
    public $promotions;

    public function __construct() {
        $this->promotions = new \Doctrine\Common\Collections\ArrayCollection();
    }
}
现在,我(在给定的代表团中)执行以下操作

在数据库中查找关系是可以的。我的促销行的委派id设置正确。
现在我的问题来了:若我要求$delegation->getPromotions(),我会得到一个空的PersistenCollection,但若我要求一个收集方法,比如$delegation->getPromotions()->count(),从这里开始一切都没问题。我没有弄错号码。现在要求$delegation->getPromotions(),之后我也正确地获得了PersistenCollection。
为什么会发生这种情况?Doctrine2何时加载集合

例如:

$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
我可以直接要求促销->getValues(),然后就可以了,但我想知道发生了什么以及如何解决它


正如Doctrine2所解释的,它几乎在任何地方都使用代理类进行延迟加载。但是访问$delegation->getPromotions()应该自动调用相应的获取。
变量转储获取空集合,但使用它(例如,在foreach语句中)工作正常。

调用
$delegation->getPromotions()
仅检索未初始化的
原则\ORM\PersistentCollection
对象。该对象不是代理的一部分(如果加载的实体是代理)

请参阅的API以了解其工作原理

基本上,集合本身也是实包装的
ArrayCollection
的代理(本例中为值持有者),在调用
PersistentCollection
上的任何方法之前,该集合将保持为空。此外,ORM还尝试优化将集合标记为
EXTRA\u LAZY
的情况,以便即使对其应用某些特定操作(如删除或添加项),也不会加载该集合

$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