symfony2.0&doctrine设置table prefix表前缀

1.打开bundle下面的 Resources/config/services.yml

2.添加prefix参数 例如默认的acme

parameters:
acmebundle.db.table_prefix: acme_

3.添加service

services:
acmebundle.tblprefix_subscriber:
class: AcmeBundle\Subscriber\TablePrefixSubscriber
arguments: [%mybundle.db.table_prefix%]
tags:
- { name: doctrine.event_subscriber }

4.添 加 AcmeBundle\Subscriber\TablePrefixSubscriber.php

namespace AcmeBundle\Subscriber;

use Doctrine\ORM\Event\LoadClassMetadataEventArgs;

class TablePrefixSubscriber 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();

    // Do not re-apply the prefix in an inheritance hierarchy.
    if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) {
        return;
    }

    if (FALSE !== strpos($classMetadata->namespace, 'AcmeBundle')) {
        $classMetadata->setPrimaryTable(array('name' => $this->prefix . $classMetadata->getTableName()));

        foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
            if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY
              && isset($classMetadata->associationMappings[$fieldName]['joinTable']['name'])) {
                $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
                $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
            }
        }
    }
}

}

ok , done

你可能感兴趣的:(doctrine,symfony)