4

Doctrine2는 언제 ArrayCollection을로드합니까?
count 또는 getValues와 같은 메서드를 호출 할 때까지 데이터가 없습니다.
여기가 제 경우입니다.Doctrine2는 메서드가 호출 될 때까지 Collection을로드하지 않습니다.

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; 
} 

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(); 
    } 
} 

지금 나는 다음과 같은 일을 할 Delegation.php

Promotion.php :이 같은 OneToMany (양방향)을 추진 엔티티와 관련이있는 위임 개체를 가지고 (주어진 대표단과 함께)

$promotion = new Promotion(); 
$promotion = new Promotion(); 
$promotion->setDelegation($delegation); 
$delegation->addPromotion($promotion); 

$em->persist($promotion); 
$em->flush(); 

다 tabase는 괜찮습니다. delegation_id가 올바르게 설정된 프로모션 행이 있습니다.
이제 내 문제가 생겼다. $ delegation-> getPromotions()를 요청하면 빈 PersistenCollection이 생기지 만 $ delegation-> getPromotions() -> count()와 같은 콜렉션의 메소드를 요청하면, 모든 것이 여기에서 괜찮습니다. 나는 번호를 올바르게 얻는다. 그 후에 $ delegation-> getPromotions()를 요청하면 PersistenCollection을 올바르게 얻을 수 있습니다.
왜 이런 일이 발생합니까? Doctrine2는 언제 Collection을로드합니까?

예 :

$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()를 사용하면 자동으로 해당 가져 오기를 호출해야합니다.
var_dump는 빈 콜렉션을 얻지 만, 예를 들어 foreach 문에서이 콜렉션을 사용하면 ok입니다.

답변

5

$delegation->getPromotions()을 호출하면 초기화되지 않은 Doctrine\ORM\PersistentCollection 개체 만 검색됩니다. 이 객체는 프록시의 일부가 아닙니다 (로드 된 엔터티가 프록시 인 경우).

어떻게 작동하는지 보려면 Doctrine\ORM\PersistentCollection의 API를 참조하십시오.

기본적으로 컬렉션 자체는 ArrayCollection의 프록시 (이 경우 값 홀더)이며 PersistentCollection의 메서드가 호출 될 때까지 빈 상태로 남아 있습니다. 또한 ORM은 컬렉션이 EXTRA_LAZY으로 표시된 경우를 최적화하려고하므로 특정 작업 (항목 제거 또는 추가)을 적용하더라도로드되지 않습니다.

관련 문제