如何截断symfony 3中的表?

时间:2016-07-20 05:22:43

标签: php symfony doctrine-orm

我想截断symfony 3.0中的表

我正在使用以下方法。

创建实体:User.php

创建存储库:UserRepository.php

/**
 * UserRepository 
 */

namespace UserBundle\Entity;

use Doctrine\ORM\EntityRepository;


class UserRepository extends EntityRepository {

    public function truncateTable() {
        $em = $this->getEntityManager();
        $dql = 'TRUNCATE TABLE UserBundle:User';
        $query = $em->createQuery($dql);

        return $query->getResult();
    }

}

当我尝试从控制器运行此代码时:我收到以下消息:

[2/2] QueryException:[语法错误]第0行,第0列:错误:预期的SELECT,UPDATE或DELETE,得到了'TRUNCATE'

任何人都可以建议我吗?

2 个答案:

答案 0 :(得分:7)

以下代码可以帮助您

    $classMetaData = $em->getClassMetadata($className);
    $connection = $em->getConnection();
    $dbPlatform = $connection->getDatabasePlatform();
    $connection->beginTransaction();
    try {
        $connection->query('SET FOREIGN_KEY_CHECKS=0');
        $q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName());
        $connection->executeUpdate($q);
        $connection->query('SET FOREIGN_KEY_CHECKS=1');
        $connection->commit();
    }
    catch (\Exception $e) {
        $connection->rollback();
    }    

答案 1 :(得分:0)

@Alexandru Cosoi的回答非常好,并且可以在PostgreSQL环境中进行细微调整:

    $classMetaData = $em->getClassMetadata($className);
    $connection = $em->getConnection();
    $dbPlatform = $connection->getDatabasePlatform();
    $connection->beginTransaction();
    try {
        // optional, but with this SET it should work with wider range of configurations
        $connection->query('SET CONSTRAINTS ALL DEFERRED');
        // more importantly - second param for getTruncateTableSql() method is set to true
        $q = $dbPlatform->getTruncateTableSql($classMetaData->getTableName(), true);
        $connection->executeUpdate($q);
        $connection->commit();
    } catch (\Exception $e) {
        var_export($e->getMessage());
        $connection->rollback();
    }

原始答案的更改会在代码中标有注释。