Skip to content

Delete product iamges and Add images programatically Issue

I have to import the product images by script for this I’m using below script but getting the error when save product.

public function __construct(
    MagentoCatalogModelProductGalleryReadHandler $readHandler,
    MagentoCatalogModelProductGalleryProcessor $galleryProcessor,
    MagentoCatalogModelResourceModelProductGallery $productGallery
) {
    $this->readHandler = $readHandler;
    $this->galleryProcessor = $galleryProcessor;
    $this->productGallery = $productGallery;
}

foreach ($data as $importImageName => $data) {
                $renamedImageName = $importImageName;
                $this->readHandler->execute($product);
                $mainDir = mb_substr($importImageName, 0, 1, "UTF-8");
                $subDir = mb_substr($importImageName, 1, 1, "UTF-8");
                $existingFilePath = $mediaPath . 'catalog/product/' . $mainDir . DIRECTORY_SEPARATOR . $subDir . '/' . $importImageName;
                $importFilePath = $mediaPath . 'import_images/' . $importImageName;
                $imageName = DIRECTORY_SEPARATOR . $mainDir . DIRECTORY_SEPARATOR . $subDir . DIRECTORY_SEPARATOR . $importImageName;
                
                    $mediaImages = $this->getMediaImages($product);
                    $imgKey = $this->getKeyByImageName($mediaImages, $importImageName);
                    if ($imgKey > 0) {
                        
                        $this->productGallery->deleteGallery($imgKey);
                        
                        $this->galleryProcessor->removeImage($product, $imageName);
                        
                        
                        
                    }
                
            }
            $product->save();

//Add New Images
if (isset($data['image_tag']) && $data['image_tag'] !== '') {
                       $imageTag = explode(',', (string) $data['image_tag']);
                        
                         $product->addImageToMediaGallery($uplodImagePath, $imageTag, false, false);
                              
                     } else {
                         
                         $product->addImageToMediaGallery($uplodImagePath, null, false, false);
            
                     }
$product->save();

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (magento.catalog_product_entity_media_gallery_value, CONSTRAINT CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID FOREIGN KEY (value_id) REFERENCES catalog_product_entity_me), query was: INSERT INTO catalog_product_entity_media_gallery_value (value_id, store_id, entity_id, label, position, disabled`) VALUES (?, ?, ?, ?, ?, ?)