I have created a custom table name as "my_topic" using InstallSchema now i want to insert data in this table. How can i do this please suggest your answers.
Magento 2 Custom Table – How to Insert Values in Custom Table
magento2table
Related Solutions
Step 1:- Create a module Stackexchange_Test using silk software module creator Click here to create a module
Step2 :- create a install script using below script in the below path app/code/Stackexchange/Test/Setup/InstallSchema.php
<?php
namespace Stackexchange\Test\Setup;
class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface
{
public function install(\Magento\Framework\Setup\SchemaSetupInterface $setup, \Magento\Framework\Setup\ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
//START: install stuff
//END: install stuff
//START table setup
$table = $installer->getConnection()->newTable(
$installer->getTable('test_table')
)->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[ 'identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true, ],
'Entity ID'
)->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[ 'nullable' => false, ],
'Name'
)->addColumn(
'number',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[ 'nullable' => false, ],
'Number'
)
->addColumn(
'city',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
255,
[ 'nullable' => false, ],
'City'
);
$installer->getConnection()->createTable($table);
//END table setup
$installer->endSetup();
}
}
?>
Now steps to create a api
Step 3: app/code/Stackexchange/Test/etc/webapi.xml
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/hello/test/" method="POST">
<service class="Stackexchange\Test\Api\TestInterface" method="setData"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
</routes>
Step 4: app/code/Stackexchange/Test/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Stackexchange\Test\Api\TestInterface" type="Stackexchange\Test\Model\Test" />
</config>
Step 5: app/code/Stackexchange/Test/Api/TestInterface.php
<?php
namespace Stackexchange\Test\Api;
interface TestInterface
{
/**
* POST for test api
* @param string[] $data
* @return string
*/
public function setData($data);
}
Step 6: app/code/Stackexchange/Test/Model/Test.php
<?php
namespace Stackexchange\Test\Model;
use Stackexchange\Test\Api\TestInterface;
class Test implements TestInterface
{
/**
* {@inheritdoc}
*/
public function setData($data)
{
$id = $data['id'];
$name =$data['name'];
$number =$data['number'];
$city =$data['city'];
//Customize the code as per your requirement.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('test_table');
$sql = "Insert Into " . $tableName . " (id, name, number, city) Values ('2','hello','50','Hyderabad')";
$connection->query($sql);
return 'successfully saved';
}
}
Step 7:- While do the changes please use di compile and clear cache and page cache and deploy the same
Step 8: Please post the data using postman app as shown in the below screenshot.
Note: Header section [{"key":"Content-Type","value":"application/json","description":""}]
Body section:-
Step 9: check the data base table 'test_table'
If you have model for your custom table then you do all these stuffs in the below way
Try this,
Di method :
Inject your model in your constructor
protected function __construct(
....
\Vendor\ModuleName\Model\ModelName $customTable,
....
)
{
...
$this->customTable = $customTable;
...
}
then on your execute function from controller
execute()
{
// insert
$model = $this->customTable->create();
// update
$model = $this->customTable->create();
$model->load('id',$id_to_update);
$model->setField_Name('values to be stored');
$model->save();
}
In order to get collection
$model = $this->customTable->create()->getCollection();
foreach($model as $item){
echo $item->getFiledName();
}
For more information Get custom table information
Hope this helps.
Best Answer
Consider your table with title,content_heading and content field are defined,
Now you have to pass inside
__consturct
field to your module factory object like below, Table with below content are automatically added.