How to get Magento 2 product image on custom phtml by product id Without loading product collection
-
08-02-2021 - |
Вопрос
I need product image on custom phtml in magento 2.
Product is collection is a array not object.
I just want to product product_base_image , without loading product collection.
I tried
<?php
namespace Dev\Core\Helper;
use Magento\Catalog\Helper\Image;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Helper\Context;
class Cart extends \Magento\Framework\Url\Helper\Data {
public function __construct(
Context $context, StoreManagerInterface $storeManger, ProductRepositoryInterface $productRepository, FormKey $formKey, Image $imageHelper
) {
$this->imageHelper = $imageHelper;
$this->productRepository = $productRepository;
parent::__construct($context);
}
public function getItemImage($productId) {
try {
$_product = $this->productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
return 'product not found';
}
$image_url = $this->imageHelper->init($_product, 'product_base_image')->getUrl();
return $image_url;
}
}
I m getting image with no issue. But i want to load image by product id without loading collection.
Решение
You can get the images directly, without loading the entire product, by using the following query:
<?php
namespace Dev\Core\Helper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\ResourceConnection;
class Cart extends \Magento\Framework\App\Helper\AbstractHelper
{
private $_connection;
public function __construct(
Context $context,
ResourceConnection $resourceConnection
)
{
$this->_connection = $resourceConnection->getConnection();
parent::__construct($context);
}
public function getItemImage($productId)
{
$select = $connection->select()
->from('catalog_product_entity_media_gallery_value', '*')
->join(
'catalog_product_entity_media_gallery',
'catalog_product_entity_media_gallery_value.value_id=catalog_product_entity_media_gallery.value_id',
array('image' => 'value')
)
->where('entity_id = ?', $productId);
try
{
return $this->_connection->fetchAll($select);
} catch (Exception $e)
{
//log or handle exception
}
}
}
Не связан с magento.stackexchange