위의 @ 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);
}
}
}
}
난이 도움이되기를 바랍니다 : 여기에
는 코드입니다.
OTM 관계가 MTM이 아닌 것이 확실합니까? –
** 편집 됨 : One to Many 대신 Many to Many 관계 ** – MedUnes