I have a custom module and i want to add remove every data including the increment id, using resource model in magento 2, i've read the solution in here but this is for magento 1, i'm not sure how to do it in magento 2, for example like this:


You can truncate table using DB Adapter and table name.

/** @var \Magento\Framework\DB\Adapter\AdapterInterface $connection */
$connection = $model->getResource()->getConnection();
$tableName = $model->getResource()->getMainTable();

Alternatively you can get DB Adapter and table name from collection, but resource model rather.

/** @var \Magento\Framework\DB\Adapter\AdapterInterface $connection */
$connection = $model->getCollection()->getConnection();
$tableName = $model->getCollection()->getMainTable();

Magento 2 can't provide directly to truncate resource collection.

Use Install/Upgrade Data script by using setup command

DB Adapter : Magento\Framework\DB\Adapter\AdapterInterface::truncateTable($tableName, $schemaName)


namespace <vender>\<module>\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

 * Category attribute Upgrade Data script
 * @codeCoverageIgnore
class InstallData implements InstallDataInterface

     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        $connection = $setup->getConnection();
        // truncate table

  • are you sure? what about dynamic index tables, flat tables, report tables? Are we need to trancate tables only using setup? I doubt it. We can use collection object as way to retrieve adapter for table and tablename for execute trancation but you can use other way to fetch this objects. – Max Jan 23 '17 at 8:38
  • @MaxStsepantsevich getConnection() is DB adapter method, so no need to load collection for truncate any table. it's will use directly – Bhavik Jan 23 '17 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.