Cretate new table to existing module in Magento2
-
15-02-2021 - |
Domanda
I have created the module and installed.
I forgot to include Setup/InstallSchema.php to create the table first time
Once the module is created can we create new table using InstallSchema.php?
I tried that is not created.
After that I used Upgradeschema.php to create the table.
By changing the version in etc/module.xml.
Now i am getting base table not found error.
I am using below code to create table in Setup/UpgradeSchema.php
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\DB\Ddl\Table;
class UpgradeSchema implements UpgradeSchemaInterface
{
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(), '2.0.1', '<')) {
$setup->getConnection()->addColumn(
$setup->getTable("product_temp_cart"),
'id',
[
"type" => Table::TYPE_INTEGER,
"identity" => true,
"nullable" => false,
"primary" => true
]
);
$setup->getConnection()->addColumn(
$setup->getTable("product_temp_cart"),
'reference_sku',
[
"type" => Table::TYPE_TEXT,
"nullable" => true
]
);
$setup->getConnection()->addColumn(
$setup->getTable("product_temp_cart"),
'product_sku',
[
"type" => Table::TYPE_TEXT,
"nullable" => true
]
);
$setup->getConnection()->addColumn(
$setup->getTable("product_temp_cart"),
'customer_id',
[
"type" => Table::TYPE_INTEGER,
"nullable" => false
]
);
$setup->getConnection()->addColumn(
$setup->getTable("product_temp_cart"),
'quote_id',
[
"type" => Table::TYPE_INTEGER,
"nullable" => true
]
);
$setup->getConnection()->addColumn(
$setup->getTable("product_temp_cart"),
'quote_id',
[
"type" => Table::TYPE_TIMESTAMP,
"nullable" => true
]
);
}
$setup->endSetup();
}
}
Can we create the table to the existing module. If yes Please anyone share me the code .
Thanks in advance
Soluzione
You can create a table by InstallSchema.php
If you forgot to create a table first time, You have to delete module entry from setup_module table. You can find your module name like Namespace_Modulename in this table. just delete your module entry and run below command
php bin/magento setup:upgrade
It will create your table.
Altri suggerimenti
UpgradeScheme works only when you need to update your existing table. so what you need to do is just find Setup_module tabel in your Database. Find the Entry of your module. Delete the entry of your module. Create Setup/InstallSchema.php write the complete script and run
php bin/magento setup:upgrade
thats all.