Doctrine2 何时加载 ArrayCollection?
直到我调用一个方法,比如 count 或 getValues,我都没有数据
这是我的情况。我有一个与促销实体具有 OneToMany(双向)关系的委托(delegate)实体,如下所示:
促销.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;
}
委托(delegate).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();
}
}
现在我执行以下操作(使用给定的代表团)
$promotion = new Promotion();
$promotion = new Promotion();
$promotion->setDelegation($delegation);
$delegation->addPromotion($promotion);
$em->persist($promotion);
$em->flush();
在数据库中查找关系是可以的。我的促销行的delegation_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
我可以直接要求promotions->getValues(),然后就可以了,但我想知道发生了什么以及如何解决它。
如flu解释 here Doctrine2 几乎在所有地方都使用代理类进行延迟加载。但是访问 $delegation->getPromotions() 应该会自动调用相应的 fetch。 var_dump 得到一个空集合,但是在 foreach 语句中使用它,例如,它工作正常。
最佳答案
调用$delegation->getPromotions()
只检索未初始化的 Doctrine\ORM\PersistentCollection
目的。该对象不是代理的一部分(如果加载的实体是代理)。
请引用 Doctrine\ORM\PersistentCollection
的API看看这是如何工作的。
基本上,集合本身又是一个真正的包装 ArrayCollection
的代理(在这种情况下是值(value)持有者)。在 PersistentCollection
上的任何方法之前保持为空叫做。此外,ORM 会尝试优化您的集合标记为 EXTRA_LAZY
的情况。这样即使您对其应用某些特定操作(例如删除或添加项目),它也不会加载。
关于collections - 在调用方法之前,Doctrine2 不会加载 Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14275661/