0

I have to display small images of products loaded by collection. Problem is (I think it is), that products (coming from collection) by default doesn't containt any images within. I have tried addAttributeToSelect(), but it seems to be more complex. Another possible solution is quering for image, inside loop for every product separately, but it seems to be impacting performance. I haven't found any predefined method to add media gallery to product collection. Has someone played with that?

EDIT: product->load('media_gallery') does work but I am not sure about it.. Is it impacting performance and is it clean way to achieve it?

3

If you look at the \Magento\Catalog\Model\ResourceModel\Product\Collection class there is actually a method addMediaGalleryData that will add the media gallery data to the product collection.

/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
$productCollection->addMediaGalleryData();

Example:

        /**
         * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
         */
        public function getProductsWithMedia()
        {
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $products */
            $products = $this->productCollection->addMediaGalleryData();

            return $products;
        }

That's it! Should give you all the data you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.