2017-09-17 3 views
0

편집 : 사용자 & 항목 : 많은Symfony3/Doctrine2에서 many-to-many 관계를 초기화

을 감안할 때 엔티티 많은 관계 대신 하나에 많은.

에는 $ 필수 부울 속성이 있습니다. 필수 항목은입니다.

사용자가 관련이 대다항목. 그는이 관련되어야하는 새로운 사용자의 생성/건설에서

(초기화) ($ 필수) 속성이 true로 설정 한 모든항목-.

Symfony3/Doctrine2에서 이러한 요구 사항을 보장하는 가장 좋은 방법은 무엇입니까? 여기에서 설명하는 것처럼

+1

OTM 관계가 MTM이 아닌 것이 확실합니까? –

+0

** 편집 됨 : One to Many 대신 Many to Many 관계 ** – MedUnes

답변

0

위의 @ kunicmarko20의 힌트에서 영감을 얻은이 솔루션이 나왔습니다.

내가 preFlush (가입했다) 이벤트, 다음, 삽입 예정 엔티티를 얻기 위해 PreFlushEventArgs을 통해 인수를 의 UnitOfWork 객체를 사용합니다. 나는 그런 기관의 사용자 인스턴스를 발생하는 경우

, 나는 그냥 모든 필수 항목을 추가 할 수 있습니다.

<?php 
// src/AppBundle/EventListener/UserInitializerSubscriber.php 
namespace AppBundle\EventListener; 

use Doctrine\Common\EventSubscriber; 
use Doctrine\ORM\Event\PreFlushEventArgs ; 

use AppBundle\Entity\User; 
use AppBundle\Entity\Item; 


class UserInitializerSubscriber implements EventSubscriber 
{ 
    public function getSubscribedEvents() 
    { 
     return array(
      'preFlush', 
     ); 
    } 

    public function preFlush (PreFlushEventArgs $args) 
    { 
     $em  = $args ->getEntityManager(); 
     $uow = $em ->getUnitOfWork(); 


     // get only the entities scheduled to be inserted 
     $entities = $uow->getScheduledEntityInsertions(); 
     // Loop over the entities scheduled to be inserted  
     foreach ($entities as $insertedEntity) { 
      if ($insertedEntity instanceof User) { 
       $mandatoryItems = $em->getRepository("AppBundle:Item")->findByMandatory(true); 
       // I've implemented an addItems() method to add several Item objects at once      
       $insertedEntity->addItems($mandatoryItems); 

      } 
     } 
    } 
} 

난이 도움이되기를 바랍니다 : 여기에

는 코드입니다.

3

이벤트 가입자를 만듭니다 (만 생성에서 원하는 경우)

http://symfony.com/doc/current/doctrine/event_listeners_subscribers.html#creating-the-subscriber-class

public function getSubscribedEvents() 
{ 
    return array(
     'prePersist', 
    ); 
} 

public function prePersist(LifecycleEventArgs $args) 
{ 
    $entity = $args->getObject(); 

    if ($entity instanceof User) { 
     $entityManager = $args->getEntityManager(); 
     // ... find all Mandatody items and add them to User 
    } 
} 

이 prePersist 기능을 추가는 사용자 개체가 있는지 확인, 데이터베이스에서 모든 항목을 얻을 필수 요소이며이를 사용자 개체에 추가해야합니다.

관련 문제