User Error: DDL statements are not allowed in transactions Magento 2.2.6
-
05-03-2021 - |
Question
I want to achieve following functionality:
Whenever user tries to insert new data, i want to remove all old data from my custom table and insert new data.
For this, i want to use truncateTable() method. i am using code from below link:
Truncate table using resource model in Magento 2
But i am getting below error when i run code:
Something went wrong while saving this configuration: User Error: DDL statements are not allowed in transaction
Is there anyway we can truncate table using code?
Note: It works with delete but reason to use truncate is to reset my custom table's auto-increment key.
Solution 2
Right now i ended up with delete instead of truncate. Actually this is not the best solution because i want to reset my auto increment key in addition to deleting all data from my table. Still someone can use this code so i am sharing here:
Solution with delete instead of truncate is as below:
<?php
class custom
{
protected $connection;
protected $dbresource;
public function __construct(\Magento\Framework\App\ResourceConnection $dbresource)
{
$this->connection = $dbresource->getConnection();
$this->dbresource = $dbresource;
}
public function mycustomfunction()
{
$table = $this->dbresource->getTableName("my_custom_table");
$this->connection->delete(
$table,
['1 = 1']
);
}
}
?>
I am still looking for a way to use truncate!!
OTHER TIPS
To remove old data from database, you can use magento code as well.
<?php
use Vendor\Extension\Model\ResourceModel\CollectionFactory;
class Yourclass
{
protected $_collectionFactory;
public function __construct(.....
CollectionFactory $collectionFactory
.....)
{
$this->_collectionFactory = $collectionFactory;
}
public function execute()
{
// To remove all old data.
$mycollection = $this->_collectionFactory->create()
->getCollection();
foreach ($mycollection as $myitem) {
$myitem->delete();
}
// Now you can do code here to add new data
}
}