Question

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();
Was it helpful?

Solution

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);

OTHER TIPS

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)

app/code/[vender_name]/[module_name]/setup/InstallData.php

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

    }
}

Create a function in your ResourceModel

app\code\Module\Namespace\Model\ResourceModel

Inventory.php

<?php

namespace Module\Namespace\Model\ResourceModel;

class Inventory extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
     protected function _construct()
     {
          $this->_init('your table name', 'primary key column name');
     }
    public function truncateTable()
        {
            if ($this->getConnection()->getTransactionLevel() > 0) {
                $this->getConnection()->delete($this->getMainTable());
            } else {
                $this->getConnection()->truncateTable($this->getMainTable());
            }
    
            return $this;
        }
}

And call this function from any file in your custom module. This must delete the table related to the resource.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top