Doctrine2何时加载ArrayCollection?
在调用count或getValues等方法之前,我没有任何数据
这是我的案例。我有一个与促销实体具有OneToMany (双向)关系的委托实体,如下所示:
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();
}
}现在,我做了类似以下的事情(使用给定的委托)
$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我可以直接请求提升->getValues(),然后让它ok,但我想知道发生了什么以及如何修复它。
正如flu解释的那样,here Doctrine2几乎在任何地方都使用代理类进行延迟加载。但是访问$delegation->getPromotions()应该会自动调用相应的fetch。
一个var_dump得到一个空集合,但是使用它-例如,在foreach语句中-它工作得很好。
发布于 2013-01-29 16:28:56
调用$delegation->getPromotions()仅检索未初始化的Doctrine\ORM\PersistentCollection对象。该对象不是代理的一部分(如果加载的实体是代理)。
具体流程请参考Doctrine\ORM\PersistentCollection的接口。
基本上,集合本身也是实际包装的ArrayCollection的代理(在本例中是值持有者),在调用PersistentCollection上的任何方法之前,它都保持为空。此外,ORM还试图优化将集合标记为EXTRA_LAZY的情况,以便即使您对其应用了某些特定操作(如删除或添加项),也不会加载它。
https://stackoverflow.com/questions/14275661
复制相似问题