一尘不染

如何在symfony2中设置表前缀

php

像问题主题一样,如何在symfony2中设置默认表前缀?

如果可以为所有实体默认设置最佳设置,但可以选择对单个实体进行覆盖。


阅读 218

收藏
2020-05-29

共1个答案

一尘不染

自己弄清楚了这一点之后,我想对如何实现这一点有所启发。

Symfony 2和Doctrine 2.1
注:我使用YML进行配置,这就是我要显示的内容。

使用说明

  1. 打开捆绑包的 Resources / config / services.yml

  2. 定义表前缀参数:
    确保更改 mybundle 和 _myprefix__

    parameters:
    mybundle.db.table_prefix: myprefix_
    
  3. 添加新服务:

services:
mybundle.tblprefix_subscriber:
    class: MyBundle\Subscriber\TablePrefixSubscriber
    arguments: [%mybundle.db.table_prefix%]
    tags:
        - { name: doctrine.event_subscriber }
  1. 创建 MyBundle \ Subscriber \ TablePrefixSubscriber.php
<?php
namespace MyBundle\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();
    if ($classMetadata->isInheritanceTypeSingleTable() && !$classMetadata->isRootEntity()) {
        // if we are in an inheritance hierarchy, only apply this once
        return;
    }

    $classMetadata->setTableName($this->prefix . $classMetadata->getTableName());

    foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
        if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY 
                && array_key_exists('name', $classMetadata->associationMappings[$fieldName]['joinTable']) ) {     // Check if "joinTable" exists, it can be null if this field is the reverse side of a ManyToMany relationship
            $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
            $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
        }
    }
}       
}
2020-05-29