2011-12-15 53 views

回答

21

截斷與學說的表是「簡單」爲:

$connection = $entityManager->getConnection(); 
$platform = $connection->getDatabasePlatform(); 

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

但是你要知道,MySQL將無法截斷任何表,一旦它有一個外鍵約束。

+0

那麼我們如何能夠truncat – Acyra 2013-02-02 13:44:41

+0

在MySQL中,你不能在你有外鍵設置... – Herzult 2013-02-04 08:47:23

+1

`的executeUpdate ()`現在已被棄用。這個答案可以更新嗎? – Alec 2015-11-12 12:01:24

12

您可以通過學說,使其忽略外鍵約束在MySQL截斷數據...

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

短變異(最有用的遷移)!

Doctrine_Manager::getInstance()->getConnection('doctrine')->getDbh()->exec("TRUNCATE name"); 
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;'); 
} 
0

如果要刪除實體,包括相關的實體最終由外鍵連接,你可以使用一個簡單的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實現的,因此可以解決您的問題。

2

如果你有外鍵的問題我一起工作:

$connection = $this->em->getConnection(); 
$connection->beginTransaction(); 

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