Magento2 – Truncate Table Using Resource Model

databasedeletemagento2modelresource-model

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:

$model->getCollection()->truncate();

Best Answer

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();
$connection->truncateTable($tableName);

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();
$connection->truncateTable($tableName);
Related Topic