php 从 Magento 中的产品集合中获取产品媒体库图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7890616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:34:48  来源:igfitidea点击:

Get Product Media Gallery Images from a Product Collection in Magento

phpmagentomagento-1.x

提问by Josh Pennington

I have a collection of products in Magento that I would like to be able to get the media gallery images out of. However I am finding that I have to iterate though my collection and load the product again to get the getMediaGalleryImages() function to work properly.

我在 Magento 中有一系列产品,我希望能够从中获取媒体库图像。但是我发现我必须遍历我的集合并再次加载产品才能使 getMediaGalleryImages() 函数正常工作。

$products = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('visibility', 4)
    ->addAttributeToFilter('status', 1);

foreach($products as $product) {
    $_product = Mage::getModel('catalog/product')->load($product->getId());

    $product->getMediaGalleryImages();      // This returns nothing
    $_product->getMediaGalleryImages();     // Returns the Collection of Images
}

Obviously I could continue just reloading the product each time, but that would add quite a bit of overhead to the time required to run this code.

显然,我可以继续每次只重新加载产品,但这会为运行此代码所需的时间增加相当多的开销。

Is there a way to add in the media gallery images to the collection?

有没有办法将媒体库图像添加到集合中?

回答by Matthias Kleine

You can use

您可以使用

$product->load('media_gallery');

before getMediaGalleryImages (on the products you loaded in the collection).

在 getMediaGalleryImages 之前(在您加载到集合中的产品上)。

回答by user2239352

One simple method for future reference:

供将来参考的一种简单方法:

Outside your foreach add

在您的 foreach 添加之外

$mediaBackend = Mage::getModel('catalog/product_attribute_backend_media');
$mediaGalleryAttribute = Mage::getModel('eav/config')->getAttribute(Mage::getModel('catalog/product')->getResource()->getTypeId(), 'media_gallery');
$mediaBackend->setAttribute($mediaGalleryAttribute);

and then do the foreach:

然后执行foreach:

foreach ($productCollection as $product) {
    $mediaBackend->afterLoad($product);
}

You will have then the gallery loaded on product.

然后,您将在产品上加载图库。

回答by Deepak Mallah

load product's cached image using collection by following codes

通过以下代码使用集合加载产品的缓存图像

Mage::helper('catalog/image')->init($_product, 'small_image')->resize(135);

//or

//或者

Mage::helper('catalog/image')->init($_product, 'thumbnail')->resize(135);

//or

//或者

Mage::helper('catalog/image')->init($_product, 'image')->resize(135);

this is the collection which i used

这是我使用的集合

$collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToSelect('small_image') //or
        ->addAttributeToSelect('thumbnail')  //or
        ->addAttributeToSelect('image');

回答by Dmitri Sologoubenko

You can create a helper class, and use it every time you need media gallery images to be loaded for a collection of products:

您可以创建一个辅助类,并在每次需要为一系列产品加载媒体库图像时使用它:

class My_Package_Helper_Media extends Mage_Core_Helper_Abstract {
    public function addMediaGalleryAttributeToProductCollection( &$productCollection )
    {
        $storeId = Mage::app()->getStore()->getId();

        $ids = array();
        foreach ( $productCollection as $product ) {
            $ids[] = $product->getEntityId();
        }

        $resource = Mage::getSingleton( 'core/resource' );
        $conn = Mage::getSingleton( 'core/resource' )->getConnection( 'catalog_read' );
        $select = $conn->select()
            ->from(
                   array( 'mg' => $resource->getTableName( 'catalog/product_attribute_media_gallery' ) ),
                   array(
                         'mg.entity_id', 'mg.attribute_id', 'mg.value_id', 'file' => 'mg.value',
                         'mgv.label', 'mgv.position', 'mgv.disabled',
                         'label_default' => 'mgdv.label',
                         'position_default' => 'mgdv.position',
                         'disabled_default' => 'mgdv.disabled'
                         )
                   )
            ->joinLeft(
                       array( 'mgv' => $resource->getTableName( 'catalog/product_attribute_media_gallery_value' ) ),
                       '(mg.value_id=mgv.value_id AND mgv.store_id=' . $storeId . ')',
                       array()
                       )
            ->joinLeft(
                       array( 'mgdv' => $resource->getTableName( 'catalog/product_attribute_media_gallery_value' ) ),
                       '(mg.value_id=mgdv.value_id AND mgdv.store_id=0)',
                       array()
                       )
            ->where( 'entity_id IN(?)', $ids );

        $mediaGalleryByProductId = array();

        $stmt = $conn->query( $select );
        while ( $gallery = $stmt->fetch() ) {
            $k = $gallery[ 'entity_id' ];
            unset( $gallery[ 'entity_id' ] );
            if ( !isset($mediaGalleryByProductId[$k]) ) {
                $mediaGalleryByProductId[$k] = array();
            }
            $mediaGalleryByProductId[$k][] = $gallery;
        }
        unset( $stmt ); // finalize statement

        // Updating collection ...
        foreach ( $productCollection as &$product ) {
            $productId = $product->getEntityId();
            if ( isset( $mediaGalleryByProductId[ $productId ] ) ) {
                $product->setData( 'media_gallery', array( 'images' => $mediaGalleryByProductId[ $productId ] ) );
            }
        }
        unset( $mediaGalleryByProductId );
    }
}

Sample usage:

示例用法:

$coll = Mage::getResourceModel('catalog/product_collection')
    ->setStoreId( Mage::app()->getStore()->getId() )
    ->addAttributeToFilter( 'sku', array( 'in' => array( 'AAA', 'BBB' ) ) );
Mage::helper('my_package/media')->addMediaGalleryAttributeToProductCollection( $coll );

回答by WonderLand

Here the code you were looking for, sorry for the delay :)

这是您正在寻找的代码,抱歉延迟:)

It come from this discussion: http://www.magentocommerce.com/boards/viewthread/17414/

它来自这个讨论:http: //www.magentocommerce.com/boards/viewthread/17414/

I just added some extra check on the number of id a and pagination

我只是对 id a 和分页的数量添加了一些额外的检查

function addMediaGalleryAttributeToCollection(Mage_Catalog_Model_Resource_Product_Collection $_productCollection)
{
    if (Mage::getStoreConfig('color_selector_plus/colorselectorplusgeneral/showonlist', Mage::app()->getStore())) {

        $_mediaGalleryAttributeId = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'media_gallery')->getAttributeId();
        $_read = Mage::getSingleton('core/resource')->getConnection('catalog_read');

        $pageCur = $_productCollection->getCurPage();
        $pageSize = $_productCollection->getPageSize();
        $offset = $pageSize * ($pageCur - 1);

        $ids = $_productCollection->getAllIds($pageSize, $offset);

        // added check on products number: if 0 ids the following query breaks
        if (count($ids) > 0) {

            $sql = '
    SELECT
        main.entity_id, `main`.`value_id`, `main`.`value` AS `file`, `value`.`disabled`,
        /*`value`.`label`, `value`.`position`, */
       /*`default_value`.`label` AS `label_default`, */
       /*`default_value`.`position` AS `position_default`, */
        `default_value`.`disabled` AS `disabled_default`
    FROM `catalog_product_entity_media_gallery` AS `main`
        LEFT JOIN `catalog_product_entity_media_gallery_value` AS `value`
            ON main.value_id=value.value_id AND value.store_id=' . Mage::app()->getStore()->getId() . '
        LEFT JOIN `catalog_product_entity_media_gallery_value` AS `default_value`
            ON main.value_id=default_value.value_id AND default_value.store_id=0
    WHERE (
        main.attribute_id = ' . $_read->quote($_mediaGalleryAttributeId) . ')
        AND (main.entity_id IN (' . $_read->quote($_productCollection->getAllIds()) . '))
    /*ORDER BY IF(value.position IS NULL, default_value.position, value.position) ASC */
';
            $_mediaGalleryData = $_read->fetchAll($sql);


            $_mediaGalleryByProductId = array();
            foreach ($_mediaGalleryData as $_galleryImage) {
                $k = $_galleryImage['entity_id'];
                unset($_galleryImage['entity_id']);
                if (!isset($_mediaGalleryByProductId[$k])) {
                    $_mediaGalleryByProductId[$k] = array();
                }
                $_mediaGalleryByProductId[$k][] = $_galleryImage;
            }
            unset($_mediaGalleryData);
            foreach ($_productCollection as &$_product) {
                $_productId = $_product->getData('entity_id');
                if (isset($_mediaGalleryByProductId[$_productId])) {
                    $_product->setData('media_gallery', array('images' => $_mediaGalleryByProductId[$_productId]));
                }
            }
            unset($_mediaGalleryByProductId);
        }
    }
    return $_productCollection;
}