如何为序列名称添加前缀?

时间:2013-10-15 11:31:24

标签: postgresql symfony doctrine-orm

我知道how to set up a table prefix in symfony2,但现在我想对postgres序列做同样的事情。我怎样才能做到这一点?这甚至可能吗?

1 个答案:

答案 0 :(得分:5)

根据这里的答案:How to setup table prefix in symfony2

  1. 打开捆绑包的Res​​ources / config / services.yml并添加:

    parameters:
        mybundle.db.sequence_prefix: myprefix_
    
  2. 添加新服务:

    services:
        mybundle.sqprefix_subscriber:
            class: MyBundle\Subscriber\SequencePrefixSubscriber
            arguments: [%mybundle.db.sequence_prefix%]
            tags:
                - { name: doctrine.event_subscriber }
    
  3. 创建MyBundle \ Subscriber \ SequencePrefixSubscriber.php

    <?php
    namespace MyBundle\Subscriber;
    
    use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
    
    class SequencePrefixSubscriber implements \Doctrine\Common\EventSubscriber
    {
        protected $prefix = '';
    
        public function __construct($prefix)
        {
            $this->prefix = (string) $prefix;
        }
    
        public function getSubscribedEvents()
        {
            return array('loadClassMetadata');
        }
    
        public function loadClassMetadata(LoadClassMetadataEventArgs $args)
        {
            $classMetadata = $args->getClassMetadata();
            if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) {
                return;
            }
    
    
            if ($classMetadata->isIdGeneratorSequence())
            {
                $newDefinition = $classMetadata->sequenceGeneratorDefinition;
                $newDefinition['sequenceName'] = $this->prefix . $newDefinition['sequenceName'];
    
                $classMetadata->setSequenceGeneratorDefinition($newDefinition);
                $em = $args->getEntityManager();
                if (isset($classMetadata->idGenerator)) {
                    $sequenceGenerator = new \Doctrine\ORM\Id\SequenceGenerator(
                        $em->getConfiguration()->getQuoteStrategy()->getSequenceName(
                            $newDefinition,
                            $classMetadata,
                            $em->getConnection()->getDatabasePlatform()),
                        $newDefinition['allocationSize']
                    );
                    $classMetadata->setIdGenerator($sequenceGenerator);
                }
            }
        }
    }
    
  4. 参考:http://www.doctrine-project.org/api/orm/2.0/class-Doctrine.ORM.Mapping.ClassMetadataInfo.html

    文档说READ-ONLY属性sequenceGeneratorDefinition所以我认为使用setter比手动更改值更清晰(但是没有getter所以我们只使用公共属性值)。