Magento – Magento 2 direct SQL query for insert not working

event-observermagento2querysql

I was trying to insert values into mlx_cot_custom_option_type_value because module files are encrypted. I want to add something after product save

I am using catalog_product_save_after event

Here is what I have tried.

    protected $_resource;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource
    ) {
        $this->_resource = $resource;
    } 
    
    $this->connection = $this->_resource->getConnection('core_write');
    $option_id = 186;
    $valueTable = 'mlx_cot_custom_option_type_value';
    $table = $this->_resource->getTableName($valueTable); 
    
    echo $sql = "Insert Into " . $table . " (option_type_id, option_id, sku, sort_order,weight) Values ('','".$option_id."','".$value['sku']."','1','')";
    $result = $this->connection->query($sql);
    echo "<pre>";
    print_r($this->connection->lastInsertId());
    die;

Output is

Insert Into mlx_cot_custom_option_type_value (option_type_id, option_id, sku, sort_order,weight) Values ('','186','Custom-Create-Any-Song-in-a-Music-Box-New','1','')

2047

$this->connection->lastInsertId() give new increment id every time but I can not see any new entry into database

When I run above query using phpmyadmin it will create new entry

Best Answer

If you guys are trying to save an attribute to product through observer "catalog_product_save_after", then this can be help:
https://webkul.com/blog/mass-update-products-attribute-magento-2/

Related Topic