如何通过magento2中的产品ID获取所有产品详细信息?我想在主页上显示带有图像的单个产品详细信息。任何帮助将不胜感激。
答案 0 :(得分:2)
为此,在Magento 2中使用Service Layer会更好。
protected $_productRepository;
public function __construct(
...
...
\Magento\Catalog\Model\ProductRepository $productRepository,
...
)
{
$this->_productRepository = $productRepository;
...
...
}
public function getProductById($id)
{
return $this->_productRepository->getById($id);
}
答案 1 :(得分:0)
尝试以下代码。它可能对你有帮助。
<?php
$productId = 10;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentproduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
?>
答案 2 :(得分:0)
use Magento\Catalog\Model\ProductFactory;
/**
* @var ProductFactory
*/
protected $_modelProductFactory;
public function __construct(
...
ProductFactory $modelProductFactory,
...
)
{
$this->_modelProductFactory = $modelProductFactory;
...
}
public function getProductInformation($productId)
{
return $this->_modelProductFactory->create()->load($productId);
}
答案 3 :(得分:0)
如果您不想获得有关产品的一些属性并希望避免加载产品,则可以使用集合来实现。只需注入课程\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
像这样:
public function __construct(
Context = $context,
//...
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
//...
array $data = []
) {
$this->_collection = $collectionFactory();
parent::__construct($context, $data);
}
然后创建一个这样的简单集合:
$productID = 10;
$product = $this->_collection
->create()
->addAttributeToSelect(['some_attribute'])
->addAttributeToFilter('entity_id', $productID)
->getFirstItem();
return $product->getSomeAttribute();
答案 4 :(得分:0)
<?php
$productId = 10;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$currentproduct = $objectManager->create('Magento\Catalog\Model\Product')-
>load($productId);
?>