Вопрос

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();
Это было полезно?

Решение

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

Другие советы

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 like this

namespace Module\Namespace\Model\ResourceModel;

class Inventory extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top