How to create a custom database table and field programetically in magento 2 - magento source24
In this blog im share code with you to How to create a custom database table and field programetically in magento 2 - in this case we require a db_scheema file in etc folder.
/app/code/VendorName/ModuleName/etc/db_scheema.xml
Now we are create a file - db_scheema.xml in etc folder
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="table_name">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" comment="Entity Id" />
<column xsi:type="varchar" name="field1" nullable="false" length="255" comment="field1" />
<column xsi:type="varchar" name="field2" nullable="false" length="255" comment="field2" />
<column xsi:type="varchar" name="field3" nullable="false" length="255" comment="field3" />
<column xsi:type="varchar" name="field4" nullable="false" length="255" comment="field4" />
<column xsi:type="timestamp" name="time_occurred" comment="Time of event" />
<column xsi:type="medium_text" name="desc" nullable="true" comment="Value" />
<constraint xsi:type="primary" referenceId="PRIMARY">
<column name="entity_id" />
</constraint>
</table>
</schema>
After add this code in db_scheema file you are changes accarding to your requirement
Now run three bellow command in your root magento project.
- php bin/magento setup:upgrade
- php bin/magento setup:static-content:deploy -f
- php bin/magento cache:flush
when command run successfully please check database
defenetely your table and table field created successfully.
Using Controller to create a custom database table and field :
<?php
namespace VendorName\ModuleName\Controller\Table;
class CreateCustomTable
{
protected $resource;
public function __construct(
\Magento\Framework\App\ResourceConnection $resource
) {
$this->resource = $resource;
}
public function execute()
{
$this->createTable();
$this->createTableSchema();
}
public function createTableCore()
{
$connection = $this->resource->getConnection();
$tableName = $this->resource->getTableName("your_table_name");
$sql = "CREATE TABLE `$tableName` (
`config_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Config Id',
`scope` varchar(8) NOT NULL DEFAULT 'default' COMMENT 'Config Scope',
`scope_id` int(11) NOT NULL DEFAULT '0' COMMENT 'Config Scope Id',
`path` varchar(255) NOT NULL DEFAULT 'general' COMMENT 'Config Path',
`value` text COMMENT 'Config Value',
PRIMARY KEY (`config_id`),
UNIQUE KEY `CORE_CONFIG_DATA_SCOPE_SCOPE_ID_PATH` (`scope`,`scope_id`,`path`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='Your Comment'";
$connection->query($sql);
}
}