Magento以编程方式删除产品图像

时间:2011-04-18 22:10:29

标签: image magento product

这必须是一个如此简单的编程任务,我绝对无法在网上找到任何有关它的信息。基本上,我正在尝试删除产品图像。我想删除产品媒体库中的所有图片。我可以这样做而不需要花费一百万行代码来完成这么简单的任务吗?

请注意我已经尝试过这个:

$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
    $gallery = $attributes['media_gallery'];
    $galleryData = $product->getMediaGallery();//this returns NULL

    foreach($galleryData['images'] as $image){
        if ($gallery->getBackend()->getImage($product, $image['file'])) {
            $gallery->getBackend()->removeImage($product, $image['file']);
        }
    }
}

这绝对不行。我试图在导入过程中删除图像,这样我就不会产生重复的图像。任何帮助将不胜感激。

14 个答案:

答案 0 :(得分:45)

好的,这就是我最终解决问题的方法。

if ($product->getId()){
    $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
    $items = $mediaApi->items($product->getId());
    foreach($items as $item)
        $mediaApi->remove($product->getId(), $item['file']);
}

这是最终让我直截了当的链接:http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media

太糟糕了,它不像$ product-> getImages()那么简单,是吗?

答案 1 :(得分:9)

在Magento 1.7.0.2中,我使用此代码删除产品库中的所有图像:

//deleting
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
    if ($gallery->getBackend()->getImage($product, $item['file'])) {
        $gallery->getBackend()->removeImage($product, $item['file']);
    }
}
$product->save();

使用Davids Tay的代码回答,我得到了错误: 致命错误:未捕获异常'Mage_Eav_Model_Entity_Attribute_Exception',消息'SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(base_xxxcatalog_product_entity_media_gallery_value,CONSTRAINT {{ 1}} FOREIGN KEY(FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID)REFERENCES`nalog_prod)'

答案 2 :(得分:8)

要从产品库中删除所有图片:

$product = Mage::getModel('catalog/product')->load($id);
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $product->getMediaGalleryImages();
foreach ($gallery as $image)
    $mediaGalleryAttribute->getBackend()->removeImage($product, $image->getFile());
$product->save();

答案 3 :(得分:5)

在删除图像期间,我发现了一件有趣的事情。当您尝试此代码时:

$galleryData = $product->getMediaGallery(); //this returns NULL

媒体库对象取决于您的产品的创建方式,如果:

$product = Mage::getModel('catalog/product')->loadByAttr('sku', $sku);

然后媒体库将是空的,如果:

$product = Mage::getModel('catalog/product')->load($id);

然后媒体库是对象,您可以使用此对象从db中删除图像。 要从文件系统中删除图像,您必须添加以下代码:

@unlink(Mage::getBaseDir('media') . '\catalog\product\' . $image['file']);

但是如果您想要更改图像并将其命名为先前的图像(image1.png替换为image1.png),在这种情况下您将遇到浏览器缓存问题。

您也可以尝试加载产品的媒体库:

$product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product);

答案 4 :(得分:3)

希望这个答案不是不受欢迎的,因为从技术上讲,它不是通过Magento编程实现的解决方案,但是我已经成功地清除了所有图库图像,仅仅是为了同样的目的,只需截断Magento 1.4.2.0中的相关表格(我相信它与1.5中的表结构相同。)

TRUNCATE TABLE `catalog_product_entity_media_gallery`
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`

然后删除 / media / catalog / product 目录中的所有图像文件。

我确实在寻找一种方法来自己编程,但发现效率更高,没有任何负面影响。

答案 5 :(得分:3)

这是我最终决定用于此任务的代码。

protected function _removeMediaGalleryImages(Mage_Catalog_Model_Product $product)
{
    $mediaGalleryData = $product->getMediaGallery();
    if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
        return;
    }

    $toDelete = array();
    foreach ($mediaGalleryData['images'] as $image) {
        $toDelete[] = $image['value_id'];
    }
    Mage::getResourceModel('catalog/product_attribute_backend_media')->deleteGallery($toDelete);
}

答案 6 :(得分:3)

     Just use this code to create .php file and place it to root folder of magento.

    <?php 
    require_once 'app/Mage.php';

    Mage::app();
    Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

    $products = Mage::getModel('catalog/product')->getCollection();
      //->addAttributeToFilter('entity_id', array('gt' => 14000));

    $mediaApi = Mage::getModel("catalog/product_attribute_media_api");

    foreach($products as $product) {
        $prodID = $product->getId();
        $_product = Mage::getModel('catalog/product')->load($prodID);
        $items = $mediaApi->items($_product->getId());
        foreach($items as $item) {
            $mediaApi->remove($_product->getId(), $item['file']);
        }
    }
?>

答案 7 :(得分:1)

这是什么

Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
    $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
    $items = $mediaApi->items($product->getId());
    $attributes = $product->getTypeInstance()->getSetAttributes();
    $gallery = $attributes['media_gallery'];
    foreach($items as $item){
        if ($gallery->getBackend()->getImage($product, $item['file'])) {
            $gallery->getBackend()->removeImage($product, $item['file']);
        }
    }
    $product->save();

答案 8 :(得分:1)

删除图片的最快方法,然后按照以下步骤操作:  删除

中的所有记录
  1. catalog_product_entity_media_gallery
  2. catalog_product_entity_media_gallery_value'
  3. 表因为magento会在那些表中保存所有产品图像数据。

    然后从管理员的索引管理索引设置图像黑色。

    然后删除图片from dir,然后转到media/catalog/product处的magento dir,并从此文件夹中删除所有文件。

    另一个过程:

    Andy Simpson,您需要一个is delete all product来自您系统delete from DB and file system的脚本。

    第1步:a php创建包含root direct of magento system的{​​{1}}。

    Mage.php at first code

    第2步:设置require_once "YOURMAGENTODIR/app/Mage.php"; umask(0); admin并设置开发者模式

    current store is

    第3步:获取Mage::app('admin'); Mage::setIsDeveloperMode(true); 并创建一个循环,逐个获取一个产品

    Product Collection

    第4步:按一个方式获取产品图片,并使用以下代码删除图片:

    $productCollection=Mage::getResourceModel('catalog/product_collection');
    

    完整代码:

    $remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
    

答案 9 :(得分:1)

如果您想要删除1000或5000等更多产品,请使用带有直接查询的底部产品。

在尝试之前,请先备份数据库

<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();
set_time_limit(0);
ini_set('display_error','1');


$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_write');

$id = 101;
$product = Mage::getModel('catalog/product')->load($id);

$q = "DELETE FROM `catalog_product_entity_media_gallery` where entity_id = '".$product->getId()."'"; 

$connection->query($q);

?>

答案 10 :(得分:0)

不久前我不得不做类似的事情 - 在导入过程中需要更换所有产品图片。

此链接有很多帮助:http://www.sharpdotinc.com/mdost/2010/03/02/magento-import-multiple-images-or-remove-images-durring-batch-import/

希望它会给你一个正确方向的推动。

答案 11 :(得分:0)

DELETE FROM catalog_product_entity_media_gallery WHERE value_id NOT IN (SELECT * FROM (SELECT MIN(value_id) FROM `catalog_product_entity_media_gallery` GROUP BY LEFT(value,17), entity_id  having count(*) > 1) x)

为什么17?

你有这样重复的expamle:

/0/0/000116810609_1.jpg

/0/0/000116810609_2.jpg

/0/0/000116810609_3.jpg

/0/0/000116810609_4.jpg

LEFT(value,17)

/ 0/0/000116810609

/ 0/0/000116810609

/ 0/0/000116810609

/ 0/0/000116810609

不,它们是重复的;)

答案 12 :(得分:0)

将以下脚本放在magento root中并执行

 <?php

  require_once("app/Mage.php");
  umask(0);
   Mage::app();
   $ob = new Clean();
   $ob->removemedia();

 Class Clean {

 function removemedia() {
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $read->select()
        ->from('catalog_product_entity_media_gallery', '*')
        ->group(array('value_id'));

$flushImages = $read->fetchAll($select);
echo count($flushImages);
$array = array();
foreach ($flushImages as $item1) {
    $array[] = $item1['value'];
}

$valores = $array;

$pepe = 'media' . DS . 'catalog' . DS . 'product';

$leer = $this->listDirectories($pepe);

foreach ($leer as $item) {
    try {
        $item = strtr($item, '\\', '/');
        if (!in_array($item, $valores)) {
            $valdir[]['filename'] = $item;
            unlink('media/catalog/product' . $item);
        }
    } catch (Zend_Db_Exception $e) {

    } catch (Exception $e) {
        //Mage::log($e->getMessage());
    }
  }
 }

function listDirectories($path) {
    if (is_dir($path)) {
       if ($dir = opendir($path)) {
        while (($entry = readdir($dir)) !== false) {
            if (preg_match('/^\./', $entry) != 1) {
                if (is_dir($path . DS . $entry) && !in_array($entry, array('cache', 'watermark'))) {
                    $this->listDirectories($path . DS . $entry);
                } elseif (!in_array($entry, array('cache', 'watermark')) && (strpos($entry, '.') != 0)) {
                    $this->result[] = substr($path . DS . $entry, 21);
                }
            }
        }
        closedir($dir);
    }
 }
 return $this->result;
 }

  }

答案 13 :(得分:0)

访问此类数据库不是一个好主意。 您可以在自定义模块中使用以下代码段删除图像(或通过更改'position'值对图像进行重新排序)(为简单起见,我使用ObjectManager,但应将ProductFactory和ProductRepositoryInterface放置在构造函数中)

$objectManager = ObjectManager::getInstance();

//Get ProductFactory in order to instatiate the Product Object 
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');

//We have to use ProductRepositoryInterface in order to save the changes bellow to the product
$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');

//Load a Product by ID in this case 1
$product = $productFactory->create()->load(1);

//Gets an array containing arrays representing each image in the gallery
$mediaGalleryEntries = $product->getMediaGalleryEntries();

//Here we delete every image, you can use conditions in foreach
foreach ($mediaGalleryEntries as $key => $imageEntry) {
    unset($mediaGalleryEntries[$key]);
}

//Finally set the altered entries and save using productRepository
$product->setMediaGalleryEntries($mediaGalleryEntries);
$productRepository->save($product);

上面的代码在Magento 2.3中进行了测试,并且还从文件系统中删除了图像。您可以使用它来删除或更改条目(更改位置,图像角色等)

要查看每个imageEntry,可以使用$ imageEntry-> getData()

访问其数据。
相关问题