从Magento的产品系列中获取产品媒体库图像

时间:2011-10-25 14:11:13

标签: php magento magento-1.x

我在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
}

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

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

5 个答案:

答案 0 :(得分:16)

您可以使用

$product->load('media_gallery');

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

答案 1 :(得分:7)

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

在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);

然后做foreach:

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

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

答案 2 :(得分:3)

通过以下代码

使用集合加载产品的缓存图像
Mage::helper('catalog/image')->init($_product, 'small_image')->resize(135);

//或

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

//或

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

这是我使用的集合

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

答案 3 :(得分:0)

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

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 );
    }
}

样本用法:

$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 );

答案 4 :(得分:-4)

这里是你要找的代码,抱歉延迟:)

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

我刚添加了一些关于id和分页数量的额外检查

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;
}