2016-07-16 117 views
6

Sto lavorando con Symfony 3.1 e Doctrine 2.5.Doctrine manyToMany restituisce PersistentCollection invece di ArrayCollection

a configurare una relazione ManyToMany come faccio sempre:

manyToMany: 
     placeServices: 
      targetEntity: Acme\MyBundle\Entity\PlaceService 
      joinTable: 
       name: place_place_service 
       joinColumns: 
        place_id: 
         referencedColumnName: id 
       inverseJoinColumns: 
        place_service_id: 
         referencedColumnName: id 

E aggiungere metodi alla mia Entity

protected $placeServices; 

    ... 

    public function __construct() 
    { 
     $this->placeServices = new ArrayCollection(); 
    } 

    ... 

    /** 
    * @return ArrayCollection 
    */ 
    public function getPlaceServices(): ArrayCollection 
    { 
     return $this->placeServices; 
    } 

    /** 
    * @param PlaceServiceInterface $placeService 
    * @return PlaceInterface 
    */ 
    public function addPlaceService(PlaceServiceInterface $placeService): PlaceInterface 
    { 
     if(!$this->placeServices->contains($placeService)) { 
      $this->placeServices->add($placeService); 
     } 

     return $this; 
    } 

    /** 
    * @param PlaceServiceInterface $placeService 
    * @return PlaceInterface 
    */ 
    public function removePlaceService(PlaceServiceInterface $placeService): PlaceInterface 
    { 
     if($this->placeServices->contains($placeService)) { 
      $this->placeServices->removeElement($placeService); 
     } 

     return $this; 
    } 

Il fatto è che, quando si carica la mia entità, la dottrina ha messo un PersistentCollection nella proprietà $ this-> placeServices. Questo non sembra un grosso problema, tranne quando costruisco un modulo per connettere queste due entità (una semplice casella di controllo multipla con tipo di modulo symfony), quando viene attivato $ form-> handleRequest(), Doctrine prova ad iniettare i nuovi dati nella mia entità, e genera un errore se il metodo get/add/remove non sta usando ArrayCollection.

Posso forzare i metodi getter/add/remove per trasformare PersistentCollection in ArrayCollection (utilizzando il metodo unwrap) ma le relazioni effettuate non vengono mantenute.

Ho trovato una soluzione alternativa, se ho impostato fetch = "EAGER" sulla relazione che la proprietà è inizializzata con ArrayCollection e la relazione sono persistenti. Ma non sono sicuro che sia una buona soluzione.

Grazie :)

+0

Potresti aggiornare con il tuo modulo symfony e l'esatto messaggio di errore? – galeaspablo

risposta

15

Basta usare Doctrine \ Common \ Collezioni \ Interfaccia Collection invece di ArrayCollection. ArrayCollection e PersistentCollection implementare questa interfaccia.

Doctrine utilizza PersistentCollection per le entità di caricamento lazy. Hai ragione, l'uso di EAGER non è sempre una buona soluzione: può causare problemi di perfomance.

+0

Grazie, ho avuto l'idea. –

Problemi correlati