Symfony 2:从特定实体生成SQL代码

问题描述:

我想从我的实体生成我的SQL。Symfony 2:从特定实体生成SQL代码

我知道的命令php app/console doctrine:schema:create --dump-sqldoctrine:schema:update,但显然没有办法过滤器上的实体甚至没有对包过滤,但仅限于EntityManager的?!

我错过了什么吗?我认为这是一个相当普遍的需求,并且很容易开发。我需要它,因为我有一个古怪的数据库与其他软件共享,这不完全是教义的想法,所以如果我不过滤我会有一些错误,或在最好的情况下,大量无用/错误的修改。

+0

你会认为这是一个常见的用例吗?如果您修改1个与另一个有关系的实体,那么为了让您的数据库保持同步,您需要更新两个实体。你能提供你为什么试图隔离给定实体的sql吗? – Chausser

+0

这是因为我有数百个实体(以前通过使用'doctrine:mapping:import'反向工程数据库生成的)。正如我在“P.S”中所说的那样,由于这些表的奇怪性,如果我'doctrine:schema:update'的一切都会产生一些错误,并且如果我纠正了这些错误,它会产生大量无用的和/或错误的SQL代码。 – Bonswouar

您可以在实体管理器进行过滤,但你需要在你的配置手动注册它们:

orm: 
    auto_generate_proxy_classes: %kernel.debug% 
    entity_managers: 
     default: 
      mappings: 
       OneBundle: 
        type: annotation 
       AnotherBundle: 
        type: annotation 
     another_entity_manager: 
      mappings: 
       SomeOtherBundle: 
        type: annotation 

这样,您就可以使用,例如:

php app/console doctrine:schema:update --dump-sql --em=another_entity_manager 

这应该只更新SomeOtherBundle中的实体的模式。

+0

所以这是一种黑客,不是吗?我将创建此实体管理器仅用于生成SQL,然后将其删除? 我想知道为什么没有更清洁的解决方案..就像一个命令行选项。 – Bonswouar

+0

这对我有帮助。谢谢 – kieste

由于只提出答案在这里不适合我,这个话题似乎是唯一一个我发现引用这个问题,有我的解决方案(请注意,我在SF2 ContainerAwareCommand使用):

namespace AppBundle\Command; 

use Doctrine\DBAL\Schema\Comparator; 
use Doctrine\ORM\Tools\SchemaTool; 
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; 

/* ... */ 

class MyCommand extends ContainerAwareCommand 
{ 
    /* ... */ 

    protected function execute(InputInterface $input, OutputInterface $output) 
    { 
     $em = $this->getContainer()->get('doctrine.orm.entity_manager'); 

     /* Doctrine tool class for create/drop/update database schemas 
     based on metadata class descriptors */ 
     $tool = new SchemaTool($em); 

     /* Doctrine tool class for comparing differences between database 
     schemas */ 
     $comparator = new Comparator(); 

     /* Create an empty schema */ 
     $fromSchema = $tool->getSchemaFromMetadata(array()); 

     /* Create the schema for our class */ 
     $toSchema = $tool->getSchemaFromMetadata(
      array($em->getClassMetadata('AppBundle:MyEntity')) 
     ); 

     /* Compare schemas, and write result as SQL */ 
     $schemaDiff = $comparator->compare($fromSchema, $toSchema); 
     $sql = $schemaDiff->toSql(
      $em->getConnection()->getDatabasePlatform() 
     ); 
     $output->writeln($sql); 
    } 
} 
+0

对代码的解释本来就不错 – Drumnbass

+1

我在代码示例中添加了一些注释 – Lulhum