Update Schema for Magento 2
-
17-03-2021 - |
Question
How do I write update schema in Magento 2 for the following:
$installer->run(
"UPDATE {$this->getTable('catalog_eav_attribute')} SET `is_visible` = 0
WHERE `attribute_id` IN(SELECT `attribute_id`
FROM {$this->getTable('eav_attribute')}
WHERE `attribute_code` LIKE 'my_name_%');"
);
Basically, I am trying to set "is_visible" to 0
in catalog_eav_attribute
table, if attribute_code
is like my_name_%
in eav_attribute
table.
Solution 2
This is what I needed:
$connection = $setup->getConnection();
$where = $connection->select()->from(
$setup->getTable('eav_attribute'),
['attribute_id']
)->where(
"attribute_code LIKE 'my_name_%'"
);
$connection->update(
$setup->getTable('catalog_eav_attribute'),
['is_visible' => false],
"`attribute_id` IN({$where->__toString()})"
);
Hope this helps someone.
OTHER TIPS
One of example of upgrade schema and data
Path should be like this: app/code/Vendor/YourModule/Setup/UpgradeSchema.php
<?php
namespace Vendor\YourModule\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
$installer = $setup;
$installer->startSetup();
if(version_compare($context->getVersion(), '1.0.1', '<')) {
$installer->getConnection()->dropColumn(
$installer->getTable('data_example'),
'created_at'
);
}
$installer->endSetup();
}
}
Note: We have to check module version of in upgrade function. In this example we upgraded module from version 1.0.0 to 1.0.1. Drop created_at column from data_example table.
Path should be like this: app/code/Vendor/YourModule/Setup/UpgradeData.php
<?php
namespace Vendor\YourModule\Setup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
class UpgradeData implements UpgradeDataInterface
{
protected $_exampleFactory;
public function __construct(\Magestore\DataExample\Model\ExampleFactory $exampleFactory)
{
$this->_exampleFactory = $exampleFactory;
}
public function upgrade( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) {
if ( version_compare($context->getVersion(), '1.0.1', '<' )) {
$data = [
'title' => "The second example title",
'content' => "The second example content"
];
$example = $this->_exampleFactory->create();
$example>addData($dalogta)->save();
}
}
}
I hope this will help
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange