3

我知道如何在 symfony2 中设置表前缀,但现在我想对 postgres 序列做同样的事情。我怎样才能做到这一点?这甚至可能吗?

4

1 回答 1

6

基于此处的答案:如何在 symfony2 中设置表前缀

  1. 打开你的包的 Resources/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);
                }
            }
        }
    }
    

参考: http: //www.doctrine-project.org/api/orm/2.0/class-Doctrine.ORM.Mapping.ClassMetadataInfo.html

文档说明READ-ONLYsequenceGeneratorDefinition属性,所以我认为使用 setter 比手动更改值更干净(但没有 getter,所以我们只使用公共属性值)。

于 2013-10-18T15:49:34.440 回答