TRUNCATE TABLE with Symfony and Doctrine
I am often importing data into a symfony project from an existing site or a CSV file and re-writing this data into the fixtures.yml is usually too complicated or time consuming so I end up writing bespoke import actions.
While I am writing these actions I often find that I have to delete the contents of the MySQL tables as you can never write the routine complete and accurate in one go so as you build it up in smaller steps you find that you have to get rid of the previously old data.
This presented me with 2 problems:-
- Using DELETE FROM [TABLENAME] does not reset the auto-incrementing fields so if you have anything that is based on the id during the rest of the import then you're going to have issues.
- There is a lot of clicking in phpMyAdmin to empty the tables, especially if you forget about the foreign key relationships.
I found that MySQL had a TRUNCATE TABLE but this is not directly available via Doctrine as the TRUNCATE TABLE is function of the type of database you are using and Doctrine cannot assume you are always using MySQL so therefore it cannot provide a generic method to call it.
Having said that it was not too difficult to run the TRUNCATE TABLE from within my Symfony project. All I had to do was add the following lines of code to an action within the actions.class.html"language-php"> $dbh = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh(); $dbh->query('TRUNCATE TABLE order_items'); $dbh->query('TRUNCATE TABLE orders'); unset($dbh);
Be careful which order you run the TRUNCATE TABLE calls so you avoid the foreign key relationship issues.
Let me know if this helps you out. Enjoy!
- November 20th, 2009