2016-07-06 69 views
0

我已經主義實體的以下設置:更新集合(onFlush)

class MainEntity 
{ 
    /** 
    * @var SecondEntity[] 
    * 
    * @ORM\OneToMany(targetEntity="SecondEntity", mappedBy="mainEntity", cascade={"persist"}) 
    */ 
    private $secondEntities; 

    /** 
    * @var integer 
    * 
    * @ORM\Column(type="integer", nullable=false, name="second_entities_count") 
    */ 
    private $secondEntitiesCount; 

    ... 
} 

class SecondEntity 
{ 
    /** 
    * @var MainEntity 
    * 
    * @ORM\ManyToOne(targetEntity="MainEntity", inversedBy="secondEntities") 
    * @ORM\JoinColumn(name="main_entity_id", referencedColumnName="id", nullable=false) 
    */ 
    private $mainEntity; 

    ... 
} 

當創建或刪除SecondEntity,我想$secondEntitiesCount在相關MainEntity將相應更新。

要做到這一點,我已經創建了一個onFlush訂戶聚集SecondEntity對象

$delsertions = array_merge(
    $unitOfWork->getScheduledEntityInsertions(), 
    $unitOfWork->getScheduledEntityDeletions() 
); 
foreach ($delsertions as $entity) { 
    if ($entity instanceof SecondEntity) { 
     $mainEntity = $entity->getMainEntity(); 

     $mainEntityMeta = $em->getClassMetadata(MainEntity::class); 
     $unitOfWork->recomputeSingleEntityChangeSet($mainEntityMeta, $mainEntity); 

     dump($mainEntity->getSecondEntities); // The creation/deletion of the current entity is not reflected here! 
    } 
} 

的問題是,在上述dump(),收集尚未因此在創建之後更新的所有計劃的缺失和插入/刪除觸發用戶的實體。例如,如果我爲給定的MainEntity創建第一個SecondEntity,則$secondEntities集合將爲空。 如果我刪除了唯一的SecondEntity,那麼$secondEntities集合仍然會在其中包含該對象。 在這種情況下,recomputeSingleEntityChangeSet()調用似乎沒有做任何事情。

我該如何強制收集才能正確更新?

回答

0

您可以創建這樣的監聽器:

use Doctrine\ORM\Event\LifecycleEventArgs; 

class UpdateMainListener 
{ 
    public function prePersist(LifecycleEventArgs $args) 
    { 
     $entity = $args->getEntity(); 

     // only act on "SecondEntity" entity 
     if (!$entity instanceof SecondEntity) { 
      return; 
     } 

     $main = $entity->getMainEntity(); 
     if(!is_null($main)) 
      $main->increaseSecondEntitiesCount(); 
    } 

    public function preRemove(LifecycleEventArgs $args) 
    { 
     $entity = $args->getEntity(); 

     // only act on "SecondEntity" entity 
     if (!$entity instanceof SecondEntity) { 
      return; 
     } 

     $main = $entity->getMainEntity(); 
     if(!is_null($main)) 
      $main->decreaseSecondEntitiesCount(); 
    } 
} 

,然後設置服務:

mybundle.prepersist.listener: 
    class: MyBundle\EventListener\UpdateMainListener 
    tags: 
     - { name: doctrine.event_listener, event: prePersist } 
mybundle.preremove.listener: 
    class: MyBundle\EventListener\UpdateMainListener 
    tags: 
     - { name: doctrine.event_listener, event: preRemove }