如何解决Magento以编程方式删除产品图片
| 这必须是一个如此简单的编程任务,我绝对无法在网上找到有关它的任何信息。基本上,我正在尝试删除产品图片。我想删除产品媒体库中的所有图像。我可以不花一百万行代码来完成这个简单的任务吗? 请注意,我已经尝试过:$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\']);
}
}
}
这绝对是行不通的。我正尝试在导入过程中删除图像,以免重复出现。任何帮助将不胜感激。解决方法
好的,这就是我最终解决问题的方式。
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()那样简单,是吗?,在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回答的代码,我得到了错误:
致命错误:消息为'SQLSTATE [23000]的未捕获异常'Mage_Eav_Model_Entity_Attribute_Exception':违反完整性约束:1452无法添加或更新子行:外键约束失败(base_xxx
.catalog_product_entity_media_gallery_value
,CONSTRAINTFK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID
外键(value_id
)参考catalog_prod) ',要从产品库中删除所有图像:
$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();
,在删除图像期间,我发现了一件有趣的事情。当您尝试此代码时:
$galleryData = $product->getMediaGallery(); //this returns NULL
媒体库对象取决于产品的创建方式,如果:
$product = Mage::getModel(\'catalog/product\')->loadByAttr(\'sku\',$sku);
如果满足以下条件,则媒体库将为空:
$product = Mage::getModel(\'catalog/product\')->load($id);
则媒体库是对象,您可以使用该对象从数据库删除图像。
要从文件系统中删除图像,您必须添加以下代码:
@unlink(Mage::getBaseDir(\'media\') . \'\\catalog\\product\\\' . $image[\'file\']);
但是在这种情况下,如果您要更改图像并将其命名为先前的图像(将image1.png替换为image1.png),则会出现浏览器缓存问题。
您也可以尝试加载产品的媒体库:
$product->getResource()->getAttribute(\'media_gallery\')->getBackend()->afterLoad($product);
,希望这个答案不是不受欢迎的,因为从技术上讲,这不是您所要求的通过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目录中的所有映像文件来进行后续操作。
我确实在寻找一种以编程方式自己执行此操作的方法,但发现此方法效率更高,并且没有副作用。,这是我最终决定用于此任务的代码。
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);
}
, 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\']);
}
}
?>
,那这个呢
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();
,删除图像的最快方法,然后按照以下步骤操作:
从中删除所有记录
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value\'
表,因为magento会将所有产品图像数据保存在那些表中。
然后从管理员的索引管理中为设置的图像黑色索引。
然后删除图像from dir
,然后转到media/catalog/product
的magento目录,并从此文件夹中删除所有文件。
另一个过程:
安迪·辛普森(Andy Simpson),您需要一个脚本,系统中的脚本为delete from DB and file system
,is delete all product
。
步骤1:在root direct of magento system
中创建a php
,其中包括Mage.php at first code
。
require_once \"YOURMAGENTODIR/app/Mage.php\";
umask(0);
第二步:设置“ 27”管理员并设置开发人员模式
Mage::app(\'admin\');
Mage::setIsDeveloperMode(true);
第三步:得到ѭ29,并创建一个循环,一个接一个地获得一个产品
$productCollection=Mage::getResourceModel(\'catalog/product_collection\');
第4步:使用以下代码将商品图片一幅化并删除一幅图片:
$remove=Mage::getModel(\'catalog/product_attribute_media_api\')->remove($product->getId(),$eachImge[\'file\']);
完整代码:
<?php
require_once \"YOURMAGENTODIR/app/Mage.php\";
umask(0);
Mage::app(\'admin\');
Mage::setIsDeveloperMode(true);
$productCollection=Mage::getResourceModel(\'catalog/product_collection\');
foreach($productCollection as $product){
echo $product->getId();
echo \"<br/>\";
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
echo $MediaCatalogDir=$MediaDir .DS . \'catalog\' . DS . \'product\';
echo \"<br/>\";
$MediaGallery=Mage::getModel(\'catalog/product_attribute_media_api\')->items($product->getId());
echo \"<pre>\";
print_r($MediaGallery);
echo \"</pre>\";
foreach($MediaGallery as $eachImge){
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
$MediaCatalogDir=$MediaDir .DS . \'catalog\' . DS . \'product\';
$DirImagePath=str_replace(\"/\",DS,$eachImge[\'file\']);
$DirImagePath=$DirImagePath;
// remove file from Dir
$io = new Varien_Io_File();
$io->rm($MediaCatalogDir.$DirImagePath);
$remove=Mage::getModel(\'catalog/product_attribute_media_api\')->remove($product->getId(),$eachImge[\'file\']);
}
}
,如果您要删除更多产品(例如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);
?>
,我不久前不得不做类似的事情-在导入期间需要替换所有产品图像。
此链接有很大帮助:http://www.sharpdotinc.com/mdost/2010/03/02/magento-import-multiple-images-or-remove-images-durring-batch-import/
希望它将为您提供正确的方向。,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?
您重复的实验如下:
/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
不,它们是重复的;),将以下脚本放置在magento根目录中并执行
<?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,\'watermark\')) && (strpos($entry,\'.\') != 0)) {
$this->result[] = substr($path . DS . $entry,21);
}
}
}
closedir($dir);
}
}
return $this->result;
}
}
,对于此类事情,访问数据库不是一个好主意。
您可以在自定义模块中使用以下代码段删除图像(或通过更改\'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()访问其数据。版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。