Magento – Magento 2.3 data insert using Data patch

databasemagento2.3

I have created a new table and added a few data using Data patch
setup/patch/data/.

Now I want to add some more data and want to update few data's so can anyone please help me or guide me that how can I do that?

Thanks

Best Answer

Inject Magento\Framework\Setup\ModuleDataSetupInterface on your data patch class:

Add below code add for adding to that table

        $this->moduleDataSetup->startSetup();
        $setup = $this->moduleDataSetup;

        $data[] = ['field1' => 'Value11', 'field2' => 'Value12'];
        $data[] = ['field1' => 'Value21', 'field2' => 'Value22'];

         $this->moduleDataSetup->getConnection()->insertArray(
            $this->moduleDataSetup->getTable('your_table'),
            ['field1', 'field2'],
            $data
        );     
        $this->moduleDataSetup->endSetup();

Full Data patch Class:

  • File location: Devbera\TestPracticsPlugin\Setup\Patch\Data\TestInfo .A nd Changes it according to your module and patch class.
<?php


namespace Devbera\TestPracticsPlugin\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class TestInfo implements DataPatchInterface
{



    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    public function __construct(
       ModuleDataSetupInterface $moduleDataSetup

     ) {

        $this->moduleDataSetup = $moduleDataSetup;

    }
    public function apply()
    {
        $this->moduleDataSetup->startSetup();
        $setup = $this->moduleDataSetup;

        $data[] = ['field1' => 'Value11', 'field2' => 'Value12'];
        $data[] = ['field1' => 'Value21', 'field2' => 'Value22'];

         $this->moduleDataSetup->getConnection()->insertArray(
            $this->moduleDataSetup->getTable('your_table'),
            ['field1', 'field2'],
            $data
        );     
        $this->moduleDataSetup->endSetup();
    }
    public function getAliases()
    {
        return [];
    }
    public static function getDependencies()
    {
        return [];
    }
}

Related Topic