我必须使用现有的数据库(不是用 Doctrine 管理的),并且我只想对这个数据库中的新表使用原则。
有没有办法告诉 Doctrine 在重新加载时不要删除整个数据库,而只删除yaml
文件中定义的模型?
我知道这是一个非常古老的问题,看来您正在使用 symfony。
尝试:
app/console --env=prod doctrine:schema:drop --full-database
这将删除数据库中的所有表。
对于 Symfony 3:
$entityManager = $container->get('doctrine.orm.entity_manager');
$entityManager->getConnection()->getConfiguration()->setSQLLogger(null);
$entityManager->getConnection()->prepare("SET FOREIGN_KEY_CHECKS = 0;")->execute();
foreach ($entityManager->getConnection()->getSchemaManager()->listTableNames() as $tableNames) {
$sql = 'DROP TABLE ' . $tableNames;
$entityManager->getConnection()->prepare($sql)->execute();
}
$entityManager->getConnection()->prepare("SET FOREIGN_KEY_CHECKS = 1;")->execute();
我用这个 Symfony 命令删除所有表:
bin/console doctrine:schema:drop --full-database --force
我在收到警告消息后添加了标志 --force 。
我的 2 美分,如果你想通过 PHP 做到这一点:
$em = ....getContainer()->get('doctrine')->getManager();
$metaData = $em->getMetadataFactory()->getAllMetadata();
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
$tool->dropSchema($metaData);
$tool->createSchema($metaData);
这有点慢,你也可以从所有表中删除所有数据:
$em = getContainer()->get('doctrine.dbal.default_connection');
foreach($em->getSchemaManager()->listTableNames() as $tableName)
{
$em->exec('DELETE FROM ' . $tableName);
}
老问题,但增加了未来的灵魂。
根据Meezaan-ud-Din 的回答,很快就找到了Zend Framework 3 + Doctrine 2
./vendor/bin/doctrine-module orm:schema-tool:drop --full-database -f --dump-sql
不要在生产中使用
orm:schema-tool:drop
“删除”数据库--full-database
清除Doctrine 管理的数据库中的所有内容!--force
(或-f
)--dump-sql
显示正在执行的 SQL。可与-f
旗帜结合。在类中找到完整的执行代码:\Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand
您可以在以下要点找到我用来从数据库中截断所有表的任务:https ://gist.github.com/1154458
核心代码是:
$this->dbh = $connection->getDbh();
$this->dbh->query(sprintf('SET FOREIGN_KEY_CHECKS = 0;'));
$tables = $connection->import->listTables();
foreach ($tables as $table)
{
$this->dbh->query(sprintf('TRUNCATE TABLE %s', $tableName));
}
$this->dbh->query(sprintf('SET FOREIGN_KEY_CHECKS = 1;'));
@ gpilotino 是的,我遇到了类似的问题。似乎没有办法从 PHPUnit 中删除和重建数据库,(Symfony 测试的未来)。
也许在“石灰”中是可能的,我不知道。
因此,我必须编写一个反向 ->save() 函数来支持数据库中的所有数据,然后重置所有序列,以便我可以进行自动化测试。
对于那些不想跟随我的挫败感的人,我尝试了两种方法:
1) 使用 symfony 内部的任务:
$optionsArray=array();
$argumentsArray=array();
$optionsArray[]="--all";
$optionsArray[]="--and-load";
$optionsArray[]="--no-confirmation";
$task = new sfDoctrineBuildTask($configuration->getEventDispatcher(), new sfFormatter());
$task->run($argumentsArray, $optionsArray);
2)在 PHP 内部从 symfony 外部执行它:
Doctrine_Manager::getInstance()->getCurrentConnection()->close();
exec('./symfony doctrine:build --all --and-load --no-confirmation');
我关闭连接的原因是 Postgres、MDBOC(我选择的数据库)不会删除具有连接的数据库。可能仍然是某种问题。我告诉你,它从来没有像简单教程显示的那么简单。使用 microslop 产品甚至更糟。
要从另一个命令中运行该命令bin/console doctrine:schema:drop --force
,请尝试以下操作:
$command = $this->getApplication()->find('doctrine:schema:drop');
$returnCode = $command->run(new ArrayInput(['--force' => true]), $output);