【问题标题】:How to truncate a table using Doctrine?如何使用 Doctrine 截断表格?
【发布时间】:2012-01-21 12:42:11
【问题描述】:

我想清空我的 MySQL 数据库中的一个表。我怎样才能用 Doctrine 做到这一点?

【问题讨论】:

    标签: mysql doctrine-orm


    【解决方案1】:

    用 Doctrine 截断表格就像“简单”一样:

    $connection = $entityManager->getConnection();
    $platform   = $connection->getDatabasePlatform();
    
    $connection->executeUpdate($platform->getTruncateTableSQL('my_table', true /* whether to cascade */));
    

    但你必须知道,一旦有外键约束,MySQL 将无法截断任何表。

    【讨论】:

    • executeUpdate() 现在已弃用。这个答案可以更新吗?
    • @Alec 您确定该方法已被弃用吗?在the code 中,该方法没有任何@deprecated
    【解决方案2】:

    您可以通过 Doctrine 截断 MySQL 中的数据,使其忽略外键约束...

    $connection->executeQuery('SET FOREIGN_KEY_CHECKS = 0;');
    $truncateSql = $platform->getTruncateTableSQL('table_name');
    $connection->executeUpdate($truncateSql);
    $connection->executeQuery('SET FOREIGN_KEY_CHECKS = 1;');
    

    【讨论】:

    • 无法识别的配置参数“foreign_key_checks”
    • 你在使用 PostgreSQL 吗?
    【解决方案3】:

    短变体(在迁移中最有用)!

    Doctrine_Manager::getInstance()->getConnection('doctrine')->getDbh()->exec("TRUNCATE name");
    

    【讨论】:

    • 这个问题与教义2有关,而不是教义1
    【解决方案4】:

    我之前将答案概括为我在项目中使用的一个不错的功能,欢迎分享。

    /** 
     * @param array $tableNames Name of the tables which will be truncated.
     * @param bool $cascade 
     * @return void
     */
     public function truncateTables($tableNames = array(), $cascade = false) {
        $connection = $this->em->getConnection();
        $platform = $connection->getDatabasePlatform();
        $connection->executeQuery('SET FOREIGN_KEY_CHECKS = 0;');
        foreach ($tableNames as $name) {
            $connection->executeUpdate($platform->getTruncateTableSQL($name,$cascade));
        }
        $connection->executeQuery('SET FOREIGN_KEY_CHECKS = 1;');
     }
    

    【讨论】:

      【解决方案5】:

      如果您想删除实体,包括最终通过外键连接的关联实体,您可以使用简单的 DQL 批处理查询而不是截断:

      $q = $em->createQuery('delete from AppBundle\Entity\Customer');
      $numDeleted = $q->execute();
      

      http://doctrine-orm.readthedocs.org/en/latest/reference/batch-processing.html#dql-delete

      只有在您正确配置了级联操作和 orphanRemoval 时,这才适用于关联,例如:

      class Customer
      {
          /**
           * @ORM\OneToOne(targetEntity="Address", cascade={"all"}, orphanRemoval=true)
           */
          public $address;
      }
      

      这不是关于 MySQL TRUNCATE 命令的直接答案,但由于它与 Doctrine 相关,因此这种方法可以解决您的问题。

      【讨论】:

        【解决方案6】:

        如果我使用的外键有问题:

        $connection = $this->em->getConnection();
        $connection->beginTransaction();
        
        $connection->query('DELETE FROM reception_detail');
        $connection->query('ALTER TABLE reception_detail AUTO_INCREMENT = 1');
        

        【讨论】:

          猜你喜欢
          • 2012-03-30
          • 1970-01-01
          • 2014-11-30
          • 2022-01-11
          • 2012-01-28
          • 2011-08-27
          • 2011-08-23
          • 2012-02-07
          • 1970-01-01
          相关资源
          最近更新 更多