圖片包給的圖片文件是子產品的圖片,如下圖:A104255是主產品的sku
<?php/*** 根據圖片包導入產品圖片,包含子產品和主產品* 子產品是作為主圖,主產品是作為附加圖片*/use Magento\Framework\App\Bootstrap;include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Framework\App\ResourceConnection $resource */
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');$obj = $bootstrap->getObjectManager();$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');/** @var \Magento\Catalog\Model\ProductFactory $productFactory */
$productFactory = $objectManager->create('\Magento\Catalog\Model\ProductFactory');/** @var \Magento\Catalog\Model\ResourceModel\MediaImageDeleteProcessor $mediaImageDeleteProcessor */
$mediaImageDeleteProcessor = $objectManager->create('\Magento\Catalog\Model\ResourceModel\MediaImageDeleteProcessor');$imageFolder = $directory->getRoot().'/pub/media/images_import';
$delUrl = $directory->getRoot().'/pub/media/catalog/product';$existsSku = [];try {// 指定搜索的文件夾和文件名進行搜索$folder = $imageFolder;//$fileName = $sku;$fileName = '*.jpg';// 執行搜索并獲取結果數組$imgfiles = searchImagesInFolder($folder, $fileName);//print_r($imgfiles);die;if ($imgfiles) {foreach ($imgfiles as $imgfile) {try {$mainImagePath = $imgfile;if(is_file($mainImagePath)){$pathArr = explode('/', $mainImagePath);$imgName = end($pathArr);$sku = explode('.', $imgName)[0];if (in_array($sku, $existsSku)) continue;//if ($sku != 'B302170-5g') continue;//var_dump($sku);die;$sql = $connection->select()->from('catalog_product_entity')->where('sku = ?', $sku);$row = $connection->fetchRow($sql);if (!$row) {echo $sku,' 不存在',PHP_EOL;continue;}$product = $productFactory->create()->loadByAttribute('sku',$sku);$rowId = $product->getRowId();if (strstr($sku, '-')){ #主圖#刪除原有的圖片/*$del = $connection->fetchAll("SELECT * from catalog_product_entity_media_gallery where value_id in( select value_id from catalog_product_entity_media_gallery_value_to_entity where row_id='{$rowId}')");foreach ($del as $key=>$value){if (file_exists($delUrl.'/'.$value['value'])) {unlink($delUrl . '/' . $value['value']);}}# 刪除產品和圖片的關聯關系$connection->query("delete from catalog_product_entity_media_gallery where value_id in( select value_id from catalog_product_entity_media_gallery_value_to_entity where row_id='{$rowId}')");$connection->query("delete from catalog_product_entity_media_gallery_value_to_entity where row_id='{$rowId}'");$connection->query("delete from catalog_product_entity_varchar where row_id='{$rowId}' and attribute_id in(87,88,89)");*/echo $sku,' 主圖',PHP_EOL;$product->setStoreId(0)->addImageToMediaGallery($mainImagePath, array('image', 'small_image', 'thumbnail'), false, false);}$product->save();#作為主產品的附加圖$sku_master = explode('-', $sku)[0] ?? '';
// var_dump($sku_master);die;if (!$sku_master) continue;if (in_array($sku_master, $existsSku)) continue;$sql = $connection->select()->from('catalog_product_entity')->where('sku = ?', $sku_master);$row = $connection->fetchRow($sql);if (!$row) {echo $sku_master,' 不存在',PHP_EOL;continue;}$product_master = $productFactory->create()->loadByAttribute('sku',$sku_master);$rowId = $product_master->getRowId();#主產品導完刪除圖片$product_master->setStoreId(0)->addImageToMediaGallery($mainImagePath, [], true, false);$product_master->save();echo $sku_master,' 子圖',PHP_EOL;}else{echo $sku." skip\n";}} catch (\Exception $e){throw new Exception($e->getMessage());}}} else {echo "沒有找到匹配的文件。",PHP_EOL;}} catch (\Exception $e){echo $e->getMessage(),PHP_EOL;
}
// }
//}function searchImagesInFolder($folder, $fileName)
{// 檢查文件夾是否存在if (!is_dir($folder)) {return [];}// 初始化結果數組$result = [];// 打開文件夾$handle = opendir($folder);// 遍歷文件夾中的文件和子文件夾while (($file = readdir($handle)) !== false) {if ($file != '.' && $file != '..') {$path = $folder . DIRECTORY_SEPARATOR . $file;// 如果是文件夾,則遞歸調用自身進行進一步搜索if (is_dir($path)) {$result = array_merge($result, searchImagesInFolder($path, $fileName));} else {// 如果是圖片文件并且文件名與模糊匹配成功,則將文件路徑添加到結果數組中if (isImageFile($file) && fnmatch("*{$fileName}*", $file)) {$result[] = $path;}}}}// 關閉文件夾closedir($handle);return $result;
}// 檢查文件是否為圖片文件
function isImageFile($file)
{$imageExtensions = ["jpg", "jpeg", "png", "gif"];$fileExtension = pathinfo($file, PATHINFO_EXTENSION);return in_array($fileExtension, $imageExtensions);
}