Magento2 Database – How to Insert Data into Custom Table in Model File

databasemagento2

Magento version: 2.0

I created a table to store some data. but maybe I have to use many file to do it from some tutorials, such as model, resource and collection folder's files.
I just save, update or delete the data into table, don't need to many works with it. So, there is simple method to do it?

Best Answer

If you wants to insert data you can try below way,

Insert Custom Query.

$this->_resources = \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Framework\App\ResourceConnection');
$connection= $this->_resources->getConnection();

$themeTable = $this->_resources->getTableName('yourtablename');
$sql = "INSERT INTO " . $themeTable . "(field1, field2) VALUES ('1', 'NameABC')";
$connection->query($sql);
Related Topic