Doctrine ORM: drop all tables without dropping dat

2020-06-08 15:10发布

I have to work with an existing database (not managed with Doctrine) and I want to use doctrine only for new tables in this db.

is there a way to tell Doctrine to not drop the entire DB on reload but only the models defined in the yaml file ?

标签: orm doctrine
8条回答
爷、活的狠高调
2楼-- · 2020-06-08 15:17

I know this a very old question, and it appears you are using symfony.

Try:

app/console --env=prod doctrine:schema:drop --full-database

This will drop all the tables in the DB.

查看更多
Emotional °昔
3楼-- · 2020-06-08 15:22

You can find a task I use to truncate all tables from a db at this gist: https://gist.github.com/1154458

The core code is:

        $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;'));
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-06-08 15:23

Old question, but adding for a future soul.

Based on Meezaan-ud-Din's answer quickly found it for Zend Framework 3 + Doctrine 2

./vendor/bin/doctrine-module orm:schema-tool:drop --full-database -f --dump-sql

Do NOT use in production

  • orm:schema-tool:drop to "drop" database
  • --full-database to wipe out everything in database which is managed by Doctrine!
  • To execute, you must use --force (or -f)
  • --dump-sql to show the SQL being executed. May be combined with the -f flag.

Complete code for execution found in class: \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand

查看更多
看我几分像从前
5楼-- · 2020-06-08 15:25

For 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();
查看更多
对你真心纯属浪费
6楼-- · 2020-06-08 15:25

I this Symfony command to drop all tables:

bin/console doctrine:schema:drop --full-database --force

I added flag --force after get a caution message.

查看更多
可以哭但决不认输i
7楼-- · 2020-06-08 15:27

Yes, surely you can use doctrine only for some tables(not all). And it won't drop all the other tables., unless you manually run

$manager->dropDatabases();

This is how you can start using Doctine for your new tables:

  1. Setup DB Connection

  2. Setup Doctrine's files/directory structure

  3. Use Command Line Interface in order to automatically generate all Doctrine models(and schema) based on DB tables(you can delete unncessesary models manually).

查看更多
登录 后发表回答