Skip to content

Instantly share code, notes, and snippets.

@collymore
Last active February 9, 2021 12:00
Show Gist options
  • Save collymore/6a420eeb3cb17292b77830a69b7a4395 to your computer and use it in GitHub Desktop.
Save collymore/6a420eeb3cb17292b77830a69b7a4395 to your computer and use it in GitHub Desktop.
Updates Magento 2 EAV values by store Id, Insert or Update store level values
/*************************************************************************************/
/** Updates EAV tables for all products, inserting or updating specific store values **/
/*************************************************************************************/
/**** Update Vars ****/
$attribute_id = 129;
$store_ids = [0,1,2];
$value = 0;
$attribute_table = 'catalog_product_entity_int';
$checkExistingValues = true;
/**** Update Vars ****/
/*** Config vars ***/
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', -1);
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
/*** Config vars ***/
$sql = "select entity_id from catalog_product_entity";
$allProducts = $connection->fetchCol($sql);
$updatedCount = 0;
$insertedCount = 0;
$notRequireUpdate = 0;
foreach($allProducts as $entity_id){
foreach($store_ids as $store_id){
if($checkExistingValues){
$query = "select value from {$attribute_table} where attribute_id = {$attribute_id} and store_id = {$store_id} and entity_id = {$entity_id};";
$existingValue = $connection->fetchOne($query);
}
if( !$checkExistingValues || !isset($existingValue) || trim($existingValue) === ''){
$query = "insert into {$attribute_table} values (null, {$attribute_id}, {$store_id}, {$entity_id}, '{$value}')";
$connection->query($query);
$insertedCount++;
}else{
if( $existingValue != $value){
$query = "update {$attribute_table} set value = '{$value}' where attribute_id = {$attribute_id} and store_id = {$store_id} and entity_id = {$entity_id}";
$connection->query($query);
$insertedCount++;
}else{
$notRequireUpdate++;
}
}
}
}
echo "updated : {$updatedCount}";
echo "\n inserted : {$insertedCount}";
echo "\n not require update : {$notRequireUpdate}";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment