douwen7603 2012-11-03 16:17
浏览 35
已采纳

Symfony2和Doctrine - 在插入时生成代码

Using Symfon2.0 and Doctrine, I am trying to do the following:

  1. Insert a new row in the database
  2. in the moment of inserting, automatically generate a code and also insert it.
  3. That code is related to the ID of the table. Something like <something>/row_id

How can I easily do this?

I've been trying Doctrine Livecycle callbacks. But:

  • PrePersist still doesn't have the ID.
  • PostPersist have the ID, but somehow the insertion has already been done and, although I can set any property from the Entity, I don't know how to make it to be persisted "again" to the database.

Any clue overthere?

Any other way to do it properly?

  • 写回答

1条回答 默认 最新

  • dsdtszi0520538 2012-12-10 23:47
    关注

    In your create controller:

    if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
    
            $entity->setCode($code);
            $em->persist($entity);
            $em->flush();
    
            return $this->redirect($this->generateUrl('entity_show'
               ,array('id' => $entity->getId())));
        }
    

    The second block ($entity->setCode...) is what you need to add and will need to be customized to suit your purposes

    Alternatively, you can use Listeners:

    <?php
    
    namespace ormed\ormedBundle\Listener;
    
    use Doctrine\ORM\Event\OnFlushEventArgs; use
    Symfony\Component\DependencyInjection\Container;
    
    class LastModifiedListener {
    
      private $container;
    
      public function __construct(Container $container){$this->container = $container;}
    
      public function onFlush(OnFlushEventArgs $eventArgs)
      {
          $entityManager = $eventArgs->getEntityManager();
          $unitOfWork = $entityManager->getUnitOfWork();
    
          foreach ($unitOfWork->getScheduledEntityInsertions() AS $entity) {
              $entity->setCode( $code );
    
              $entityManager->persist($entity);
              $classMetadata = $entityManager->getClassMetadata(get_class($entity));
              $unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity);
    } } }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?