Magento – How to truncate magento table using collection

collection;databasemagento-1.7magento-1.8

I have a custom table. I want to truncate the table using Magento collection without SQL query.

Hope someone will provide some useful information.

Best Answer

Magento does not have a support for this (as far as I know).
But you can implement a method in your resource model (not the collection resource model) that will truncate the table.
Something like this:

public function truncate() {
    $this->_getWriteAdapter()->query('TRUNCATE TABLE '.$this->getMainTable());
    return $this;
}

Then you can call it in your code:

Mage::getResourceModel('[module]/[entity]')->truncate();

But this is a very dangerous approach. The truncate statement breaks the transaction, so it cannot be rolled back in case you need to.
I suggest deleteing every entity in the table instead.

$collection = Mage::getModel('[module]/[entity]')->getCollection();
foreach ($collection as $item) {
    $item->delete();
}

The down side of this is that it doesn't reset the increment id of the table. But it's safer.

EDIT.
To update the increment id of the main table you can add a new method in your resource model that does something like this.

public function changeAutoIncrement($increment = 1) {
    $this->_getWriteAdapter()->query('ALTER TABLE '.$this->getMainTable().' AUTO_INCREMENT = '. $increment);
}

Then call your method in the code:

Mage::getResourceModel('[module]/[entity]')->changeAutoIncrement();